在python中,如何在每次调用函数时覆盖到文件并附加到函数内部的文件?
我有这样一个函数:在python中,如何在每次调用函数时覆盖到文件并附加到函数内部的文件?,python,file,io,Python,File,Io,我有这样一个函数: def process_corpus(xml_dir, top): for dir_file in os.listdir(xml_dir): dir_file_path = os.path.join(xml_dir, dir_file) if os.path.isfile(dir_file_path): with open(dir_file_path) as f: page = f.read()
def process_corpus(xml_dir, top):
for dir_file in os.listdir(xml_dir):
dir_file_path = os.path.join(xml_dir, dir_file)
if os.path.isfile(dir_file_path):
with open(dir_file_path) as f:
page = f.read()
v = mapping(dir_file_path, top)
print "filename"
print dir_file
for i in range(len(v)):
f1 = open("/Users/akritibahal/Downloads/stanford-corenlp-2012-07-09/file1.txt".format(i), "w")
if v[i] == 1:
print (str(i+1) + ":" + str(v[i]))
f1.write (str(i+1) + ":" + str(v[i]) + " ")
f1.close()
f.close()
此函数用于打开包含文件的目录,然后读取每个文件。
我希望每次调用函数时,数据都应该被覆盖到文件file1.txt中,当读取每个文件并进行计算时(如果对其进行了计算),数据应该附加到该文件(file1.txt)。如何做到这一点?来自:
更新:
您还可以查看如何很好地解释
open()
功能。我不确定我是否理解,但您可以通过传递“a”
:open(文件名,“a”)
来打开一个文件进行追加。您需要对您的问题进行一些澄清,因为您不清楚您在问什么
with open("file1.txt", "w") as file1:
file1.write("The file is truncated and overwritten with this")
with open("file1.txt", "a") as file1:
file.write("This is appended to the end of the file, regardless of the current seek position)
with open("file1.txt", "r") as file1:
data = file1.read() # Cannot write to the file here
with open("file1.txt", "r+") as file1:
data = file1.read()
file1.write("This mode allows you to both read and write to the file")