我是新手到Python。我有一个代码,我必须将这些内容再次写入到同一个文件中,但是当我这样做时,它会清除我的内容。请帮助解决它。蟒蛇明确的内容写在同一个文件
我应该如何修改我的代码,这样的内容将在同一个文件中写回?
我的代码:
import re
numbers = {}
with open('1.txt') as f,open('11.txt', 'w') as f1:
for line in f:
row = re.split(r'(\d+)', line.strip())
words = tuple(row[::2])
if words not in numbers:
numbers[words] = [int(n) for n in row[1::2]]
numbers[words] = [n+1 for n in numbers[words]]
row[1::2] = map(str, numbers[words])
indentation = (re.match(r"\s*", line).group())
print (indentation + ''.join(row))
f1.write(indentation + ''.join(row) + '\n')
写回文本到同一文件将让你不高兴。 – 2014-09-04 14:06:15
通过修改代码,我的意思是创建新的写文件可能是相同的文件名? – 2014-09-04 14:08:30
@adsqwqwe如果你只需要追加到文件,那么你就有一个答案,否则你需要将文件加载到内存中来修改它,或者你可以加载到新的临时文件,然后将其重命名。 – JosEduSol 2014-09-04 14:10:18