There are many ways to read and write files in Python, and you can choose different methods according to actual needs. The following will introduce several commonly used file reading and writing methods, and give code examples.
# 打开文件 file = open("file.txt", "w") # 写入文件 file.write("Hello, world!") # 关闭文件 file.close() # 打开文件 file = open("file.txt", "r") # 读取文件内容 content = file.read() print(content) # 关闭文件 file.close()
# 写入文件 with open("file.txt", "w") as file: file.write("Hello, world!") # 读取文件 with open("file.txt", "r") as file: content = file.read() print(content)
# 打开文件 file = open("file.txt", "w") # 写入文件 file.write("Hello, world!") # 关闭文件 file.close() # 打开文件 file = open("file.txt", "r") # 读取部分内容 content = file.read(5) print(content) # 关闭文件 file.close()
# 打开文件 file = open("file.txt", "w") # 写入多行内容 lines = ["line 1", "line 2", "line 3"] file.writelines(lines) # 关闭文件 file.close() # 打开文件 file = open("file.txt", "r") # 逐行读取文件内容 line = file.readline() while line: print(line) line = file.readline() # 关闭文件 file.close()
The above are several commonly used file reading and writing methods, which are suitable for different scenarios and needs. When using functions and methods related to file reading and writing, you must remember to close the file in time to avoid problems such as resource leakage.
The above is the detailed content of What are the ways to read and write files in Python?. For more information, please follow other related articles on the PHP Chinese website!