python操作文件程序
时间: 2023-10-12 08:04:39 浏览: 80
python习题
Python可以很方便地操作文件,下面是一个简单的示例程序,可以实现文件的读取、写入、追加、复制、重命名和删除等操作:
```python
import os
# 读取文件
def read_file(filename):
with open(filename, "r") as f:
content = f.read()
print(content)
# 写入文件
def write_file(filename, content):
with open(filename, "w") as f:
f.write(content)
# 追加文件
def append_file(filename, content):
with open(filename, "a") as f:
f.write(content)
# 复制文件
def copy_file(src, dst):
with open(src, "rb") as f1, open(dst, "wb") as f2:
while True:
buf = f1.read(1024 * 1024)
if not buf:
break
f2.write(buf)
# 重命名文件
def rename_file(src, dst):
os.rename(src, dst)
# 删除文件
def delete_file(filename):
os.remove(filename)
# 测试程序
if __name__ == "__main__":
filename = "test.txt"
content = "hello, world!\n"
write_file(filename, content)
append_file(filename, "welcome to Python!\n")
read_file(filename)
copy_file(filename, "test_copy.txt")
rename_file(filename, "test_new.txt")
delete_file("test_copy.txt")
delete_file("test_new.txt")
```
注意,以上示例中的代码仅供参考,实际使用时还需要考虑文件的打开方式、异常处理、目录操作等问题。另外,文件操作时需要注意文件的编码、大小写、权限等问题,避免出现不必要的错误。
阅读全文