There are four ways to read text documents using Python: Read the entire file content directly Read the file content line by line and store it in a list Iterate the file content line by line Specify the encoding, reading mode and newline of the file Symbols and other optional parameters
How to use Python to read text documents
Direct method:
<code class="python">with open("filename.txt", "r") as f: contents = f.read()</code>
Read line by line:
<code class="python">with open("filename.txt", "r") as f: lines = f.readlines()</code>
Iterate line by line:
<code class="python">with open("filename.txt", "r") as f: for line in f: # 对每一行进行操作</code>
Other optional parameters :
Example:
Read a file named "example.txt" and print its contents:
<code class="python">with open("example.txt", "r") as f: contents = f.read() print(contents)</code>
Read "example .txt" file and store it in a list:
<code class="python">with open("example.txt", "r") as f: lines = f.readlines() print(lines)</code>
Read the "example.txt" file line by line and print each line:
<code class="python">with open("example.txt", "r") as f: for line in f: print(line)</code>
The above is the detailed content of How to read text documents in python. For more information, please follow other related articles on the PHP Chinese website!