Python文件操作小结


#!/usr/bin/env python

#####
fp=open("ip.txt", "r")
file_lines=fp.readlines()
for each_line in  file_lines:
	print each_line,
fp.close()
#####
file_object=open("ip.txt", "r")
file_content=file_object.read()
print file_content,
file_object.close()
#####
file_object=open("ip.txt", "r")
while True:
	file_line=file_object.readline()
	if file_line:
		print file_line,
	else:
		break
file_object.close()
#####
说明如下:python中read() readline()以及readlines()区别
  • read() 每次读取整个文件,它通常将读取到底文件内容放到一个字符串变量中,也就是说 fp.read() 返回的是一个字符串;
  • readline()每次只读取文件的一行,通常也是读取到的一行内容放到一个字符串变量中,返回str类型;
  • readlines()每次按行读取整个文件内容,将读取到的内容放到一个列表中,返回list类型。

 

Update@2014年12月22日 20:49:48

最近经常会需要用到Python读写文件(将代码执行过程中的打印内容/结果写入文件),但发现不怎么熟练,为了避免这一问题,现在在原文的基础上再次总结一下Python读写文件的方法:

步骤1.先使用open()打开一个文件,创建一个文件对象

https://docs.python.org/2/library/functions.html#open

open(name[, mode[, buffering]])
Open a file, returning an object of the file type described in section File Objects. If the file cannot be opened, IOError is raised. When opening a file, it’s preferable to use open() instead of invoking the file constructor directly.

提示:open()函数成功执行后返回的文件对象是可迭代的(iterable)。

步骤2.文件读取

https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

一个文件读取/写入的例子:
import zlib
fp = open('aaa', 'rb')
con_0 = fp.read()
fp.close()

print len(con_0)
decompressed_data = zlib.decompress(con_0, 16+zlib.MAX_WBITS)
print len(decompressed_data)

fp = open('bbb', 'wb')
fp.write(decompressed_data)
fp.close()
步骤3.文件写入

http://stackoverflow.com/questions/12377473/python-write-versus-writelines-and-concatenated-strings

write()和writelines()方法的异同:

writelines() expects a list of strings[or any iterable object producing strings], while write() expects a single string.(write()是将一个字符串写入文件;writelines()是将一个字符串列表/可迭代对象写入文件


 

如何将Unicode字符串写入文件?

python how to write unicode to a txt file

http://stackoverflow.com/questions/6048085/python-write-unicode-text-to-a-text-file

>> txt = u"ähnlicher als gewöhnlich üblich"
>> import codecs
>> codecs.open("tmp.txt", "wb", "utf8").write(txt)
>> codecs.open("tmp.txt", "rb", "utf8").read()
In [3]: codecs.open?
Type:        function
String form: <function open at 0x02957430>
File:        c:python27libcodecs.py
Definition:  codecs.open(filename, mode='rb', encoding=None, errors='strict', buffering=1)
Docstring:
Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding.

Note: The wrapped version will only accept the object format defined by the codecs, i.e. Unicode objects for most builtin codecs. Output is also codec dependent and will usually be Unicode as well.

Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. The default file mode is 'rb' meaning to open the file in binary read mode.

encoding specifies the encoding which is to be used for the file.

errors may be given to define the error handling. It defaults to 'strict' which causes ValueErrors to be raised in case an encoding error occurs.

buffering has the same meaning as for the builtin open() API. It defaults to line buffered.

The returned wrapped file object provides an extra attribute. encoding which allows querying the used encoding. This attribute is only available if an encoding was specified as parameter.

即,使用codecs模块在打开文件的时候指定编码。


《 “Python文件操作小结” 》 有 2 条评论

  1. Python中的文件读取在特定条件下进行下一行的读取等跳过操作
    https://stackoverflow.com/questions/5108734/python-readlines-stop-then-continue-in-the-nextline
    `
    使用 yield 关键字。

    def line_search():
    fp = open(‘sample.txt’)
    for line in fp:
    if line.startswith(‘keyword’):
    yield line

    all_lines = []
    for line in line_search():
    all_lines.append(line)

    print all_lines
    `

    Python – 当打开文件并循环每一行时跳到下一行
    https://stackoverflow.com/questions/24274169/python-skip-to-next-line-when-opening-file-and-looping-each-line

    Read file from line 2 or skip header row
    https://stackoverflow.com/questions/4796764/read-file-from-line-2-or-skip-header-row
    `
    使用 next 方法。

    with open(fname) as f:
    next(f)
    for line in f:
    #do something
    `

    Python逐行读取文件内容
    https://www.cnblogs.com/sysuoyj/archive/2012/03/14/2395789.html
    `
    f = open(“foo.txt”) # 返回一个文件对象
    line = f.readline() # 调用文件的 readline()方法
    while line:
    print line, # 后面跟 ‘,’ 将忽略换行符
    # print(line, end = ”)   # 在 Python 3中使用
    line = f.readline()
    f.close()
    `

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注