Python学习之文件操作

Python 处理普通文件(flat file)

Python处理普通文件时,把数据从一个文件中读入内存,然后从内存写入文件。

使用open()打开文件

读写一个文件之前要打开它,格式如下:

fileobj = open(filename, mode)

• fileobj 是open() 返回的文件对象;

• filename 是该文件的字符串名;
• mode 是指明文件类型和操作的字符串。

mode的第一个字母表明对文件的操作类型:

• r 表示读模式。
• w 表示写模式。如果文件不存在则新创建,如果存在则重写新内容。
• x 表示在文件不存在的情况下新创建并写文件。
• a 表示如果文件存在,在文件末尾追加写内容。

mode的第二个字母表示要操作的文件的类型:

• t(或者省略)代表文本类型;
• b 代表二进制文件。

使用read()/readline()/readlines()读取文本文件 

read()

使用read()函数能够一次性读取文件所有内容,如下:

>>> f_read = open('text2.txt','rt')
>>> content = f_read.read()
>>> print(content)
 This is the first line
this is the second line
third line
...
Nth line
End.

>>> f_read.close()
>>> 

需要注意的是,如果被读取的文件特别大(几个G),可能会出问题,因为它会尝试将几个G的文件内容一次性读入内存中。

可以设置read()每次读取的大小,如下:

>>> f1 = open('text2.txt','rt')
>>> chunk = 15
>>> text_content = ''
>>> while True:
    part = f1.read(chunk)
    if not part:
        break
    text_content += part

    
>>> f1.close()
>>> print(text_content)
 This is the first line
this is the second line
third line
...
Nth line
End.

>>> 

readline()

readline()每次只读入文件的一行,如下:

>>> with open('text2.txt','rt') as f1:
    while True:
        line = f1.readline()
        if not line:
            break
        print(line)

        
 This is the first line

this is the second line

third line

...

Nth line

End.

>>> 

readlines()

readlines()函数调用时每次也是读取一行,但它返回的是单行字符串的列表,如下:

>>> with open('text2.txt','rt') as f1:
    lines = f1.readlines()

    
>>> lines
[' This is the first line
', 'this is the second line
', 'third line
', '...
', 'Nth line
', 'End.
']
>>> 

另外,最简单的读取文件的方式是通过迭代器,每次也会返回一行,如下:

>>> with open('text2.txt','rt') as f1:
    for line in f1:
        print(line)

        
 This is the first line

this is the second line

third line

...

Nth line

End.

>>> 

使用write()/print()写文本文件

 write()可以返回写入文件的字节数。

>>> f_obj = open('test.txt','wt')
>>> f_obj.write("Hello world!!")
13
>>> f_obj.close()
>>> 

会在python shell所在的目录生成一个test.txt文件,如下:

使用print()也可以写入文本,如下:

>>> f_obj2 = open('test2.txt','wt')
>>> print("this content is from print function",file=f_obj2)
>>> f_obj2.close()
>>> 

使用wirte()和使用print()的区别

print()会默认在每个参数后面添加空格,在每行结束处添加换行

如果文件已经存在,使用模式x可以避免重写文件,如下:

>>> f_obj = open('text2.txt','xt')
Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    f_obj = open('text2.txt','xt')
FileExistsError: [Errno 17] File exists: 'text2.txt'
>>> 

 二进制文件读写

如果文件模式中采用了'b',那么文件会以二进制模式打开,这种情况下,读写的是字节而不是字符串。

二进制模式写入一个文件:

>>> fout = open('bfile', 'wb')
>>> fout.write(bdata)
256
>>> fout.close()

二进制模式读取一个文件:

>>> fin = open('bfile', 'rb')
>>> bdata = fin.read()
>>> len(bdata)
256
>>> fin.close()

seek() & tell() 

Python在读写文件的过程中都会跟踪文件中光标的位置。使用函数seek()能够跳转到文件指定字节偏移量的位置。使用函数tell()能够返回光标距离文件开始处的字节偏移量。

其他操作

1 使用with 自动关闭文件

在完成对文件的读写操作后需要关闭文件。使用with的好处就是不需要使用close()来关闭文件。wih操作完成后文件会被自动关闭。

如下:

>>> with open('relativity', 'wt') as fout:
...   fout.write(poem)
...

2 修改文件内容

修改文件内容,可以使用两个文件:原文件和临时文件,读取原文件的每一行,对符合要求的行做修改,并把每一行都写入临时文件中,最后使用临时文件覆盖掉原文件。

在使用os.rename的时候,如果目标文件已经存在的情况下,使用os.rename(临时文件,目标文件)时会报错(file exists)。所以,在使用os.rename之前先用os.remove()删除目标文件。

original_file='/home/test/test.o'
temp_file='/home/test/temp'
f_original=open(original_file,'r')
f_temp=open(temp_file,'w')
for line in f_original.readlines():
    if keywork in line:
        line=line.replace(line,'This is a new line')
    f_temp.write(line)
f_temp.close()
f_original.close()

if os.path.isfile(original_file):
    os.remove(original_file)
os.rename(temp_file,original_file)

3 处理Excel文件

处理Excel文件的话,需要模块xrld,可以在 https://pypi.python.org/pypi/xlrd 上下载安装。

打开Excel文件

excel_file='/home/test/list.xls'
data = xlrd.open_workbook(excel_file)  #打开 excel文件
table=data.sheets()[0]    #获取第一个sheet
原文地址:https://www.cnblogs.com/cedrelaliu/p/5140213.html