使用标准库fileinput.input遍历后文本文件被清空

使用标准库fileinput.input遍历后文本文件被清空

python标准库中的fileinput,使用input函数遍历指定的txt文件,发现脚本退出后,文件被清空了。请教文本被清空的原因。

环境:
py3.7
pycharm 2018.1.4
win10

正常运行代码:

import os

import fileinput

def proc_file():

for line in fileinput.input(file_name, inplace=1):

print(line.replace("test", "py"))

proc_file()

文本内容:
test 11
test 22

运行脚本后文本内容:
py 11

py 22

异常代码:

import os

import fileinput

def proc_file():

for line in fileinput.input(file_name, inplace=1):

a = 0 # 不对读出的文本做处理,就会脚本退出后文本就会清空

proc_file()

在pycharm中或者在命令行环境下,运行异常代码后,文本都会被清空,请赐教


回答:

https://docs.python.org/2/lib...

Optional in-place filtering: if the keyword argument inplace=1 is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.<some extension>'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read.

"inplace=1" 会用标准输出替换文件内容

以上是 使用标准库fileinput.input遍历后文本文件被清空 的全部内容, 来源链接: utcz.com/p/937613.html

回到顶部