Home  >  Article  >  Backend Development  >  How to read text documents in python

How to read text documents in python

下次还敢
下次还敢Original
2024-04-20 17:50:181043browse

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 read text documents in python

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 :

  • encoding: Specify the encoding of the file, such as "utf-8".
  • mode: Read mode, "r" is read-only, "w" is write-only, "a" is append.
  • newline: is used to control the newline character. The default value is the operating system default newline character.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn