How does Python handle libraries for text files?

There are many libraries in Python for handling text files, here are some commonly used ones:

  1. the open() function
# 打开文件并读取内容
file = open('filename.txt', 'r')
content = file.read()
file.close()

# 打开文件并写入内容
file = open('filename.txt', 'w')
file.write('Hello, World!')
file.close()
  1. OS library
import os

# 读取文件内容
content = os.popen('cat filename.txt').read()

# 写入文件内容
os.popen('echo "Hello, World!" > filename.txt')
  1. Input/Output library
import io

# 打开文件并读取内容
with io.open('filename.txt', 'r', encoding='utf-8') as file:
    content = file.read()

# 打开文件并写入内容
with io.open('filename.txt', 'w', encoding='utf-8') as file:
    file.write('Hello, World!')
  1. CSV library
import csv

# 读取CSV文件内容
with open('filename.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# 写入CSV文件内容
with open('filename.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['John', '25'])
  1. pandas library
import pandas as pd

# 读取CSV文件内容
df = pd.read_csv('filename.csv')

# 写入CSV文件内容
df.to_csv('filename.csv', index=False)

These are just some commonly used libraries, you can choose other suitable libraries according to your specific needs.

bannerAds