我第一次执行此程序时,除了新行之外,生成的文件中没有任何内容。但是第二次执行它时,它正确写入'out.txt',但第一次执行的新行仍然存在。为什么第一次不能正常工作?
bhaarat = open('bhaarat.txt', 'r+')
bhaarat_read = bhaarat.read()
out = open('out.txt', 'r+')
out_read = out.read()
bhaarat_split = bhaarat_read.split()
for word in bhaarat_split:
if word.startswith('S') or word.startswith('H'):
out.write(word + "\n")
bhaarat.write('\n23. English\n')
print out_read
print bhaarat_read
bhaarat.close()
out.close()
答案 0 :(得分:0)
这是Windows的问题。解决方法(see python mailing list)是使用
f.seek(f.tell())
在使用read()
选项之一打开的文件write()
上调用f
和+
之间的。
根据您的问题,您必须先使用bhaarat.seek(bhaarat.tell())
并在使用bhaarat_read = bhaarat.read()
向其发送文件之前致电bhaarat.write('\n23. English\n')
。您的out
也一样。
在Python3中,这个问题已得到解决,因此还有一个原因需要切换:)
EDIT
以下代码适用于我。文件bhaarat.txt
和out.txt
必须同时存在。
bhaarat = open('bhaarat.txt', 'r+')
bhaarat_read = bhaarat.read()
bhaarat.seek(bhaarat.tell())
out = open('out.txt', 'r+')
out_read = out.read()
out.seek(out.tell())
bhaarat_split = bhaarat_read.split()
for word in bhaarat_split:
if word.startswith('S') or word.startswith('H'):
out.write(word + "\n")
bhaarat.write('\n23. English\n')
print out_read
print bhaarat_read
bhaarat.close()
out.close()