Python 为什么我的脚本会将每个输入字符串写入输出文件两次?
当我看到它写的东西时,它总是双重的。例如,如果我写“dog”,我会得到“dogdog”。为什么? 读取和写入文件,文件名取自命令行参数:Python 为什么我的脚本会将每个输入字符串写入输出文件两次?,python,python-2.7,Python,Python 2.7,当我看到它写的东西时,它总是双重的。例如,如果我写“dog”,我会得到“dogdog”。为什么? 读取和写入文件,文件名取自命令行参数: from sys import argv script,text=argv def reading(f): print f.read() def writing(f): print f.write(line) filename=open(text) #opening file reading(filename) filename.
from sys import argv
script,text=argv
def reading(f):
print f.read()
def writing(f):
print f.write(line)
filename=open(text)
#opening file
reading(filename)
filename.close()
filename=open(text,'w')
line=raw_input()
filename.write(line)
writing(filename)
filename.close()
正如我所说的,我得到的输出是我给出的输入的双倍值。你得到的是双倍值,因为你写了两次
1) 从函数调用
def writing(f):
print f.write(line)
2) 使用filename写入文件。写入(行)
使用此代码:
from sys import argv
script,text=argv
def reading(f):
print f.read()
def writing(f):
print f.write(line)
filename=open(text,'w')
line=raw_input()
writing(filename)
filename.close()
而且也不需要关闭文件两次,一旦完成了所有读写操作,就可以关闭它。如果要显示每一行,然后再写一行新行,您可能应该先读取整个文件,然后在写入新内容时循环行 这是你可以做到的。当您将
与open()
一起使用时,您不必关闭()
文件,因为这是自动完成的
from sys import argv
filename = argv[1]
# first read the file content
with open(filename, 'r') as fp:
lines = fp.readlines()
# `lines` is now a list of strings.
# then open the file for writing.
# This will empty the file so we can write from the start.
with open(filename, 'w') as fp:
# by using enumerate, we can get the line numbers as well.
for index, line in enumerate(lines, 1):
print 'line %d of %d:\n%s' % (index, len(lines), line.rstrip())
new_line = raw_input()
fp.write(new_line + '\n')
嗯,我想显示文件中的内容,并在上面写一些其他文本。谢谢你的帮助。没有提到为什么文件会被写入两次。请参阅@bhansa的答案。您正在向该文件写入两次