文件操作
1、打开文件
打开不存在的文件:
f=open('text.txt')#打开一个不存在的文件夹
Traceback (most recent call last):
File "<ipython-input-1-fae403acd124>", line 1, in <module>
f=open('text.txt')#打开一个不存在的文件夹
FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'
f=open('text.txt','w')#打开一个不存在的文件夹
第一种运行方式会报错,第二种不会报错,会新建一个文件,区别是第二种代码加了文件的mode(访问模式),w的意思是,打开一个文件只用于写入。如果文件已存在,则覆盖,如果文件不存在,则新建一个文件。而第一种方式没有输入mode,则默认访问方式为r,即以只读方式打开文件并且指针放在文件头部,固会报错。
2、关闭文件
f.close
Out[3]: <function TextIOWrapper.close()>
关闭文件这个结果在显示页面中看不到。
3、在文件中进行写入操作
f=open('text.txt','w')#打开一个不存在的文件夹
f.write('hello world')
f.close
Out[8]: <function TextIOWrapper.close()>
然后打开python中的文件,找到text这个txt文件,可以发现输入后的结果如下:
close是为了之后别的程序可以继续访问这个文件。
4、读取某几个字符
f=open('text.txt','r')#r表示只读模式
result= f.read(3)#读取3个字符
print(result)
hel
result= f.read(3)#读取3个字符
print(result)
lo
result= f.read(3)#读取3个字符
print(result)
wor
result= f.read(3)#读取3个字符
print(result)
ld
第一次打开的时候读前n个字符(定位在文件头部),每次重复执行命令的时候则往后移动n格。
5、读取行(readline)
f=open('text.txt','r')#r表示只读模式
result= f.readline()#读取一行
print(result)
hello world
readlines读取结果和readline不太相同
f=open('text.txt','r')#r表示只读模式
result= f.readlines()#读取一行
print(result)
['hello world']
对hello world 复制成五行以后再readlines:
f=open('text.txt','r')#r表示只读模式
result= f.readlines()#读取一行
print(result)
['hello world\n', 'hello world\n', 'hello world\n', 'hello world\n', 'hello world']
形成有五个元素的列表,将文档读成列表。
6、对每行进行标号
i=1;
for temp in result:
print('%d:%s'%(i,temp))
i+=1
1:hello world
2:hello world
3:hello world
4:hello world
5:hello world
如果用的是readline,(此时对第一行加了–1,以便区分)则:
f=open('text.txt','r')#r表示只读模式
result= f.readline()#读取一行
print('1:%s'%result)
1:hello world--1
result= f.readline()#读取一行
print('1:%s'%result)
1:hello world
可以发现,readline每次只能读一行,不够高效。
7、可以用os进行重命名
import os
os.rename('text.txt','text1.txt')