python 读写文件
关于文件的基本命令:
close: 关闭文件。
read : 读取文件的内容
readline: 读取文件的一行内容
truncate: 清空文件
write(‘stuff‘): 将“stuff”写入文件
seek(0): 将读写位置移动到文件开头
#写入内容到文件from sys import argv script,filename = argv print(f"找到我们的{filename}文件") print("正在打开文件") target = open(filename,‘w‘) print("正在清理文件内容") target.truncate() print("现在输入写入每一行的内容") line1 = input("line1:") line2 = input("line2:") line3 = input("line3:") print("把你的内容写入文本") target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) print("正在关闭文件") target.close()
#文件复制 from os.path import exists out1 = input("输入复制源文件:") out2 = input("输入复制目的文件:") if exists(out1): out1_file = open(out1) file_data = out1_file.read() out1_file.close() else: print(f"{out1}文件不存在") if exists(out2): out2_file = open(out2,‘w‘) out2_file.write(file_data) out2_file.close() else: print(f"{out2}文件不存在")
#一个文件内容复制到另一个文件 from sys import argv from os.path import exists script,from_file,to_file = argv print(f‘从{from_file}复制到{to_file}‘) in_file = open(from_file) indata = in_file.read() print(f"这个文件的的字节长度是{len(indata)}") print(f"输出文件是否存在:{exists(to_file)}") out_file = open(to_file,‘w‘) out_file.write(indata) print(‘关闭所有文件‘) out_file.close() in_file.close()
相关推荐
EdwardSiCong 2020-11-23
yungpheng 2020-10-19
jipengx 2020-11-12
橄榄 2020-11-03
lyqdanang 2020-11-02
wservices 2020-10-30
onepiecedn 2020-10-29
数据人 2020-10-26
dfphoto 2020-10-16
hackerlpy 2020-09-07
tianyayi 2020-08-16
Dullonjiang 2020-08-15
fengling 2020-08-15
wordmhg 2020-08-06
guotiaotiao 2020-08-06
zhangsyi 2020-07-28
千锋 2020-07-27
ahnjwj 2020-07-28