首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >两天研习Python基础(十) 文件处理

两天研习Python基础(十) 文件处理

作者头像
王诗翔呀
发布2020-07-02 16:05:15
4690
发布2020-07-02 16:05:15
举报
文章被收录于专栏:优雅R优雅R

open函数

  • 语法:open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
>>> import locale
>>> locale.getpreferredencoding()
'UTF-8'
  • 本文中我们将看到下面一些文件操作模式
    • r打开文件用来读入
    • w打开文件用来写入
    • a打开文件用来追加
  • 默认是文本模式,所以传入rrt等价
    • 对于二进制模式,将对应是rbwb等等
  • locale.getpreferredencoding()给出默认使用的编码方式
  • Python文档 - open[1]
  • Python文档 - 标准编码[2]

读文件

#!/usr/bin/python3

# 打开文件,逐行读入并打印
filename = 'hello_world.py'
f = open(filename, 'r', encoding='ascii')

print("Contents of " + filename)
print('-' * 30)
for line in f:
    print(line, end='')

f.close()

# 'with'是一种更简单的方式,会自动处理文件关闭
filename = 'while_loop.py'

print("\n\nContents of " + filename)
print('-' * 30)
with open(filename, 'r', encoding='ascii') as f:
    for line in f:
        print(line, end='')
  • 通常默认编码为'UTF-8',这里设定为'ascii'
  • 使用with并设定f为文件句柄是一种习惯
$ ./file_reading.py
Contents of hello_world.py
------------------------------
#!/usr/bin/python3

print("Hello World")


Contents of while_loop.py
------------------------------
#!/usr/bin/python3

# continuously ask user input till it is a positive integer
usr_string = 'not a number'
while not usr_string.isnumeric():
    usr_string = input("Enter a positive integer: ")

如果文件不存在

#!/usr/bin/python3

with open('xyz.py', 'r', encoding='ascii') as f:
    for line in f:
        print(line, end='')
  • 如果文件没有找到会返回错误
$ ./file_reading_error.py
Traceback (most recent call last):
  File "./file_reading_error.py", line 3, in <module>
    with open('xyz.py', 'r', encoding='ascii') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'xyz.py'
$ echo $?
1
  • 使用read()读入整个文件内容为单个字符串
>>> f = open('hello_world.py', 'r', encoding='ascii')
>>> f
<_io.TextIOWrapper name='hello_world.py' mode='r' encoding='ascii'>
>>> print(f.read())
#!/usr/bin/python3

print("Hello World")
  • 逐行读入使用readline()
>>> f = open('hello_world.py', 'r', encoding='ascii')
>>> print(f.readline(), end='')
#!/usr/bin/python3
>>> print(f.readline(), end='')

>>> print(f.readline(), end='')
print("Hello World")

>>> f.close()
>>> print(f.readline(), end='')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
  • 使用readlines()读入所有行为列表
    • 注意复数形式
>>> f = open('hello_world.py', 'r', encoding='ascii')
>>> all_lines = f.readlines()
>>> all_lines
['#!/usr/bin/python3\n', '\n', 'print("Hello World")\n']
  • 检查文件是否关闭
>>> f = open('hello_world.py', 'r', encoding='ascii')

>>> f.closed
False

>>> f.close()
>>> f.closed
True

写文件

#!/usr/bin/python3

with open('new_file.txt', 'w', encoding='ascii') as f:
    f.write("This is a sample line of text\n")
    f.write("Yet another line\n")
  • 使用write()方法打印一个字符串到文件
  • 想要添加文本到已存在的文件,使用a模式而不是w模式
$ ./file_writing.py
$ cat new_file.txt
This is a sample line of text
Yet another line

使用fileinput就地编辑

#!/usr/bin/python3

import fileinput

with fileinput.input(inplace=True) as f:
    for line in f:
        line = line.replace('line of text', 'line')
        print(line, end='')
  • 当程序运行时,将被修改的文件都会指定为命令行参数[3]
  • 注意print函数必须用f.write替代
  • 因为迭代的每行已经有换行符,尾部给空字符串
  • Python文档 - fileinput[4]
$ ./inplace_file_editing.py new_file.txt
$ cat new_file.txt
This is a sample line
Yet another line

$ # 要改变当前目录中所有以.txt结尾的文件,使用
$ ./inplace_file_editing.py *.txt

$ # stdin也可以作为输入
$ echo 'a line of text' | ./inplace_file_editing.py
a line
  • 指定文件名和备份扩展
# 在程序内指定文件名
with fileinput.input(inplace=True, files=('file1.txt', 'file2.txt')) as f:

# 要创建一个不修改的文件备份,传入对应的备份参数
with fileinput.input(inplace=True, backup='.bkp') as f:

参考资料

[1]Python文档 - open: https://docs.python.org/3/library/functions.html#open

[2]Python文档 - 标准编码: https://docs.python.org/3/library/codecs.html#standard-encodings

[3]命令行参数: ./Command_line_arguments.md

[4]Python文档 - fileinput: https://docs.python.org/3/library/fileinput.html

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 优雅R 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • open函数
  • 读文件
  • 写文件
  • 使用fileinput就地编辑
  • 参考资料
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档