仅替换文本文件第一行中的某些元素

Isa*_*aac 1 python file-io replace

感谢您对我可能愚蠢的问题感兴趣.

我有一个文本文件,并希望替换某些"NaN"元素.

我通常使用file.replace函数来通过整个文本文件更改具有一定数量的NaN.
现在,我想在仅文本文件的第一行而不是全文中用一定数量的NaN替换.
你能给我一个暗示这个问题吗?

guk*_*off 5

您只能读取整个文件,为第一行调用.replace()并将其写入新文件.

with open('in.txt') as fin:
    lines = fin.readlines()
lines[0] = lines[0].replace('old_value', 'new_value')

with open('out.txt', 'w') as fout:
    for line in lines:
        fout.write(line)
Run Code Online (Sandbox Code Playgroud)

如果你的文件不是很大,你可以只使用.join():

with open('out.txt', 'w') as fout:
    fout.write(''.join(lines))
Run Code Online (Sandbox Code Playgroud)

如果它真的很大,你可能会更好地同时读取和写入行.