Python - file处理
""" 文件操作步骤: 1,打开文件 2,读 3,写 4,关闭文件 (写入的数据,临时保存在内存中,当关闭文件以后,才会从内存中存放到文件中) """ # f1 = open(r"D:\python\学习资料\test.txt",'w+') # # f1 = open(r"D:\python\学习资料\test.txt",'w+',encoding="UTF-8 be") # print(f1.read()) # f1.newlines # f1.write("\n333") # print(f1.read()) # f1.close() # # print("file path:{}".format(f1.name)) # print("file mode:{}".format(f1.mode)) # print("file status:{}".format(f1.closed)) # # 如果出现IOError报错,可以使用try """ try: read, open,write finally: close """ """ 作用:同try..finally..的效果一样 """ # with open(r"D:\python\学习资料\test.txt",'r+') as f: # print(f.read()) # f.write("111\n") # f.write("222\n") # f = open(r"D:\python\学习资料\test2.txt",'r') # f2 = open(r"D:\python\学习资料\test3.txt",'w') # # f.write("111\n") # # f.write("222\n") # print(f.readline()) # position = f.tell() # print(position) # print("==============") # position = f.seek(0,0) # print(position) # # print(f.read()) # f_text = f.read() # # f2.write(f_text) # # f.close() # f2.close() # # print(f.closed) """ 随堂测试: 1,接收用户输入的file 2,备份file -> file[备份] """ old_name = input("please input you backup file:") index = old_name.rfind('.') # 找到这个字串对应的最后下标,找到就返回索引,找不到就返回-1 # 新文件名 new_name = old_name[:index] + "【备份】" + old_name[index:] print(old_name) print(new_name) with open(old_name) as f: new_text = f.read() print(new_text) print(type(new_text)) if new_text == "": pass else: with open(new_name, 'w+') as f2: f2.write(new_text)
***
# new class OS
# import OS
# mkdir,..... perform the function from OS.

浙公网安备 33010602011771号