>>> import locale
>>> locale.getpreferredencoding()
'UTF-8'r打开文件用来读入w打开文件用来写入a打开文件用来追加r和rt等价rb,wb等等locale.getpreferredencoding()给出默认使用的编码方式#!/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='')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 $?
1read()读入整个文件内容为单个字符串>>> 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#!/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='')print函数必须用f.write替代$ ./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