I. Read the entire contents of the file
Before reading the file, we create a text file as the source file.
my name is joker, I am 18 years old, How about you?
How to read the entire contents of the file, we write to the file.
with open('') as file_obj: content = file_obj.read() print(content)
It is important to note that you need to place the file in the same directory as the file.
The result after running is as follows:
Explanation: The open function takes one argument, which is the name of the file whose contents are to be read, and returns an object representing the file after the call, which Python stores in a variable (file_obj), and the keyword with closes the file when we no longer need to use it.
The above code in the open() function is passed a relative path, relative path from the current file () where the folder to find the specified file (), if the file is not in the current folder, you can use an absolute path.Linux system absolute path such as:
/home/joker/dic like this, or an absolute path like C:/pyhton_workspace/dic for Windows.
Second, read the contents of the file line by line
file_name = '' with open(file_name) as file_obj: for content in file_obj: print(content)
The console prints the following:
Explanation: In the above program, as Python reads the file and stores it in the object file_obj, we loop over the object to traverse each line of the file, but find that there are more than one blank line because there are invisible line breaks in this file and the print statement statement also adds a line break, so there are two line breaks at the end of each line. To eliminate the extra blank lines, call the rstrip() method in the print statement as follows:
file_name = '' with open(file_name) as file_obj: for content in file_obj: print(())
The console prints the following:
Now, and is the same as reading the output of the entire file.
to this article on the Python method of reading data from a file steps to this article, more related Python file to read data content please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!