zyh3033 发表于 2017-4-25 11:50:53

Python复习笔记—文件

1. open打开文件
  open(filename, mode)
  mode:只读(r),只写(w),追加(a),读写(r+),二进制读(rb,wb,ab, r+b),

2. 读文件
  read(),读全部文件
  read(),读size个字节
  readline()读开始一行
  readlines()读所有行到一个list

3. 写文件
  write(string),写入字符串,非字符串必须先转换为字符串

4. 随机读写
  seek(offset, from),
  from:0文件开始;1当前位置,2文件末尾

5. 安全读写
  用open语句,会自动关闭文件,甚至是在发生异常的情况下
  with open(filename, mode) as f :
  dosomething(f)

6. 序列化和反序列化
  pickle.dump(obj, f),序列化到文件;
  obj = pickle.load(f),反序列化;

7. 例子
  


>>> #write file
>>> f = open('D:/temp/python_test.txt', 'w')
>>> f.write('abcdefghijklmnopqrstuvwxyz\r\n')
>>> f.write('0123456789\r\n') #\r\n is line separator on Windows
>>> val = ('value is', 12)
>>> f.write(str(val)) # nonstring object should be convert string first
>>> f.close()
>>> #read file
>>> f = open('D:/temp/python_test.txt', 'r')
>>> f.read()
"abcdefghijklmnopqrstuvwxyz\r\n0123456789\r\n('value is', 12)"
>>> f.seek(0, 0)
>>> f.tell()
0L
>>> f.readline()
'abcdefghijklmnopqrstuvwxyz\r\n'
>>> f.readlines()
['0123456789\r\n', "('value is', 12)"]
>>> f.seek(0, 0) # move to begin of the file
>>> f.read(3)
'abc'
>>> f.seek(4, 1) # skip 4 bytes
>>> f.read(1)
'h'
>>> f.seek(-2, 2) # Go to the 3rd byte before the end
>>> f.read(1)
'2'
>>> f.seek(0, 0)
>>>
>>> # read line by line
>>> for line in f :
print line

abcdefghijklmnopqrstuvwxyz

0123456789

('value is', 12)
>>> f.close()
>>> # read with 'with'
>>> with open('D:/temp/python_test.txt', 'r') as f:
for line in f :
print line

abcdefghijklmnopqrstuvwxyz

0123456789

('value is', 12)
>>> # serialize/unserialize object
>>> with open('D:/temp/python_test.txt', 'w') as f :
pickle.dump(, f)
>>> with open('D:/temp/python_test.txt', 'r') as f :
x = pickle.load(f)
print x


 
页: [1]
查看完整版本: Python复习笔记—文件