python 文件 笔记
文件对象 反斜杠在python字符串中是一个特殊字符,需要转义:使用两个反斜杠 或在路径前加r "C:\\Windows\\Temp" r"C:\windows\Temp" 1 编写文本文件 file对象代表对一个文件的连接,而不是文件本身,如果试图打开或者向一个不存在的文件写数据,python将自动创建该文件。如果文件存在,会删除它并创建一个新文件。 def make_text_file(): a=open('E://test.txt',"w") "w" 参数:向文件中写数据,如果没有指定参数,则从文件中读数据,若文件不存在,将抛出异常。 a.write("this is how you create a new text file") a.close() import os def make_another_file(): if os.path.isfile('E://test.txt'): 检查文件是否已经存在 print("you are trying to create a file that already exists!") else: f=open('E://text.txt',"w") f.write("2 this is how you create a new text file") f.close() 打开一个文件时可以指定一个相对路径(相对于当前目录的路径