在Python程序中读取和写入文件,主要依赖于内置的open函数及其相关方法。以下是具体的操作方法:
读取文件- 读取整个文件内容到字符串:
- 使用with open as file:语句打开文件。
- 使用file.read方法读取整个文件内容。
- 例如:pythonwith open as file: content = file.read print2. 逐行读取文件: 同样使用with open as file:语句打开文件。 使用for line in file:循环逐行读取文件内容。 例如:pythonwith open as file: for line in file: print) # 使用strip去除每行末尾的换行符
写入文件- 覆盖文件内容:
- 使用with open as file:语句打开文件。
- 使用file.write方法写入内容。
- 例如:pythoncontent_to_write = "Hello, World! This is a test."with open as file: file.write2. 追加内容到文件末尾: 使用with open as file:语句打开文件。 同样使用file.write方法追加内容。 例如:pythonadditional_text = "Appending some more text... "with open as file: file.write
注意事项- 'r'模式用于读取文件,'w'模式用于写入文件,'a'模式用于追加内容。
- encoding='utf8'参数确保正确处理文本文件的编码。
- 使用with语句可以确保文件在使用后自动关闭,避免资源泄露。
- 其他模式如'x'、'b'、'+'等也可以根据需要使用。