Skip to content
Python

文件读写

读写文件的多种方式。

#file#io

Code

python
# Read entire file
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()

# Read line by line
with open("file.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

# Write file
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("Hello World\n")

# Append write
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("new log\n")