首页 > 开发 > Python > 正文

文件的创建,写入,关闭,删除

2016-07-31 22:42:21  来源:慕课网
  例子1:
#创建文件context = '''hello worldhello China'''f = open('hello.txt','w') #打开文件,若想保存在不同路径,格式为f = open('d:/file/hello.txt','w')f.write(context) #把字符串写入文件f.close() #关闭文件  程序运行后,会在此程序报存路径上,自动生成一个hello.txt文件,并将context中的内容写入hello.txt文件中,若已有同名文件,会将此文件中的内容清除,再将内容写入。
例子2:按行读取readline()
f = open('hello.txt') while True: line = f.readline() #line = f.readline(2)每行每次读2个字符,直到行末尾 if line: print("line") else: breakf.close()  例子3:多行读取 readlines()
f = open('hello.txt')lines = f.readlines()for line in lines: print(line)  例子4:一次性读取 read()
f = open('hello.txt')context = f.read()print(context)  例子5:使用writelines()写文件
f = open("hello.txt","w+")li = ["hello world\n","hello china\n"]f.writelines(li)f.close()  或者
f = open("hello.txt","w+")li = "hello world \n hello China\n"f.write(li)f.close()  例子6:追加
f = open("hello.txt","a+")new_context = "goodbey"f.write(new_context)f.close()  使用writelines()写文件的速度更快,若需要写入文件的字符串非常多,可以使用writelines()方法提高效率,如需要写入少量的字符串,使用write()方法即可
例子7:删除文件
import osif os.path.exists("hello.txt"): os.remove("hello.txt")  或者
import ostry: if os.path.exists("hello.txt") os.remove("hello.txt")except: pass #不知何时会执行到except语句  或者
import osopen("hello.txt","w")try: if os.path.exists("hello.txt"): os.remove("hello.txt")except: pass  或者
import osf = open("hello.txt","w") #存在hello.txt文件,会清除内容,不存在hello.txt文件,会生成一个空文件try: if os.path.exists("hello.txt"): os.remove("hello.txt")except: pass