Home > Backend Development > Python Tutorial > How to read text documents in python

How to read text documents in python

下次还敢
Release: 2024-04-20 17:50:18
Original
1105 people have browsed it

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>
Copy after login

Read line by line:

<code class="python">with open("filename.txt", "r") as f:
    lines = f.readlines()</code>
Copy after login

Iterate line by line:

<code class="python">with open("filename.txt", "r") as f:
    for line in f:
        # 对每一行进行操作</code>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template