在python中,读写文件有3个步骤:
1.调用open( )函数,返回一个File对象,打开文件。
2.调用File对象的read( )或write( )方法,进行读写操作。
3.调用File对象的close( )方法,关闭该文件。
读取文件
>>> >>> test1File = open('C:\\Users\\Administrator\\Desktop\\testdir\\test1.txt') #打开文件
>>> test1Content=test1File.read() #读取文件
>>> print(test1Content) #打印出文件内容
Hello weorld!
Hello,Xiaotie!
调用readlines( )逐行读取文件。每个字符串就是文本中的每一行,除了最后一行,每行以一个换行字符\n结束。
>>> test1File = open('C:\\Users\\Administrator\\Desktop\\testdir\\test1.txt')
>>> test1Content=test1File.readlines()
>>> print(test1Content)
['Hello weorld!\n', 'Hello,Xiaotie!']
写入文件
write()方法不会像print( )函数那样,在字符串的末尾自动添加换行字符,必须要自己去添加。
>>> baconFile=open('bacon.txt','w') #以写模式打开文件,由于文件bacon.txt不存在,python自动创建新的空文件bacon.txt
>>> baconFile.write(