tedwhy 发表于 2018-8-13 06:32:56

Python IO编程——文件读写

1.1   文件读写
1.1.1   读文件
  >>> f = open('/root/python/hello.py','r')    #标识符r表示读
  >>> f =open('/root/python/hello1.py', 'r')   #文件不存在报错
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  FileNotFoundError: No such fileor directory: '/root/python/hello1.py'
  读取文件内容
  >>> f.read()   #str对象
  "#!/usr/bin/python\nprint('hello,world')\n"
  >>> f.close()   #关闭文件
  文件调用读写中可能造成IOError,一旦出错后面的f.close()将不会被调用,这时我们用如下语句:
  >>> try:
  ...    f = open('/root/python/hello.py', 'r')
  ...    print(f.read())
  ... finally:
  ...    if f:
  ...      f.close()
  ...
  #!/usr/bin/python
  print('hello,world')
  python给我们提供了更简单的方法
  >>> withopen('/root/python/hello.py', 'r') as f:
  ...    print(f.read())
  ...
  #!/usr/bin/python
  print('hello,world')
  注意:
  read()会一次性读取文件的全部内容,使用文件较小;
  read(size)每次最多读取size个字节的内容,不确定文件的大小;
  readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list,适合配置文件。
  >>> withopen('/root/python/hello.py', 'r') as f:
  ...    for line in f.readlines():
  ...      print(line.strip())
  ...
  #!/usr/bin/python
  print('hello,world')
1.1.2   File-like object
  像open()函数返回的这种有个read()方法的对象,在Python中统称为file-like Object。file-like Object不要求从特定类继承,只要写个read()方法就行。
1.1.3   二进制文件
  前面讲的默认都是读取文本文件,并且是UTF-8编码的文本文件。要读取二进制文件,比如图片、视频等等,用'rb'模式打开文件即可。
  >>> f =open('/Users/michael/test.jpg', 'rb')
  >>> f.read()
  b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...'# 十六进制表示的字节
1.1.4   字符编码
  要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件:
  >>> f =open('/Users/michael/gbk.txt', 'r', encoding='gbk')
  >>> f.read()
  '测试'
  遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,因为在文本文件中可能夹杂了一些非法编码的字符。遇到这种情况,open()函数还接收一个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略:
  >>> f =open('/Users/michael/gbk.txt', 'r', encoding='gbk',errors='ignore')
1.1.5   写文件
  python写文件时,并不要求目标文件一定存在。
  # ls test.txt
  test.txt
  # rm -f test.txt
  # python
  Python 3.5.0b4 (default, Jul1 2016, 21:28:36)
   onlinux
  Type "help","copyright", "credits" or "license" for moreinformation.
  >>> f = open('/root/python/test.txt','w')   #w表示写文本文件,wb表示写二进制文件
  >>> f.write('Hello,python!')
  14
  >>> f.close()
  >>>
  # cat test.txt
  Hello, python!
  对同个文件再次写会覆盖
  >>> withopen('/root/python/test.txt', 'w') as f:    #也可encoding指定字符编码
  ...    f.write('abc')
  ...    f.write('123')
  ...
  3
  3
  >>>
  #
  # cat test.txt
  abc123# python
  Python 3.5.0b4 (default, Jul1 2016, 21:28:36)
   onlinux
  Type "help","copyright", "credits" or "license" for moreinformation.
  >>> withopen('/root/python/test.txt', 'w') as f:
  ...    f.write('NEW')
  ...
  3
  >>>
  #
  # cat test.txt
  NEW
页: [1]
查看完整版本: Python IO编程——文件读写