This question already has answers here:
How to reading .txt file and rewriting by adding space after specific position / index for each line in python
                                
                                    (2个答案)
                                
                        
                                6个月前关闭。
            
                    
运行代码时,它可以正确执行,并且不会出现错误,并且可以预期结果,但是文件不会被“覆盖”。解决办法是什么?

即使代码正确并且没有错误,也要重写文件!

space_indecies = [2, 5, 8]

with open("data.txt", "r") as file:
    lines = file.read().split("\n")
    newlines = []
    for line in lines:
        line = line.rstrip()
        for n, i in enumerate(space_indecies):
            line = line[:i + n] + ' ' + line[n + i:]
        newlines.append(line)
    with open("data.txt", "w") as newfile: # Maybe wrong with this sentence
        newfile.write("\n".join(newlines))


预期结果 :
如果文件中的写入语句有错误,请正确修改它,并得到相同的结果。

最佳答案

newlines = []
with open("data.txt", "r") as file:
    lines = file.read().split("\n")
    for line in lines:
        line = line.rstrip()
        for n, i in enumerate(space_indecies):
            line = line[:i + n] + ' ' + line[n + i:]
        newlines.append(line)
with open("data.txt", "w") as newfile:# Maybe wrong with this sentence
    newfile.write("\n".join(newlines))

10-07 19:45
查看更多