Cria 发表于 2020-5-25 18:01:58

关于python读写文件

使用文本文件读写方法,创建文件data.txt的备份文件data[复件].txt,要求读取原文件中的数据,并写入备份文件。

Twilight6 发表于 2020-5-25 18:01:59

本帖最后由 Twilight6 于 2020-5-25 18:58 编辑

重新修改了下,而且加了备注~
file_path = input('请输入需要备份的文件名:')
with open(file_path,encoding='utf-8') as f:
    txt = f.read()   # 读取文件内容 并赋值给 txt 用于备份
   
(file_suffix,file_name) = file_path[::-1].split('.',1)# 分离文件后缀与文件名 防止文件中有.导致分离错误所以倒头来只分离1次

with open(file_name[::-1]+'[复件]'+file_suffix[::-1],'w',encoding='utf-8') as f:
    # 新建备份文件,因为上面倒过文件名所以重新倒回正,否则文件名会出现倒至
   
    f.write(txt)# 写入备份文件内容
香蕉君 你懂得

qiuyouzhi 发表于 2020-5-25 18:11:44

f = open("data.txt", encoding="utf-8")
temp = f.read()
f.close()
f = open("data[复件].txt", 'w')
f.write(temp)
f.close()

Cria 发表于 2020-5-25 18:13:50

Twilight6 发表于 2020-5-25 18:10
香蕉君 你懂得

日常一py交易{:10_256:}

瞳中雪 发表于 2020-5-25 21:02:01

日常py

ForPorsche 发表于 2020-5-25 23:13:50

{:5_109:}

f = open(r'd:\test.txt','r')
t = f.read()
with open('d:\data[复件].txt','w+',encoding='utf-8') as x:
          x.write(t)
f.close()

zwhe 发表于 2020-5-26 15:43:14

{:5_92:}
页: [1]
查看完整版本: 关于python读写文件