仅在文本文件的第一行中替换某些元素 [英] Replace certain element in only first line of the text file

查看:80
本文介绍了仅在文本文件的第一行中替换某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a text file and would like to replace certain elements which is "NaN".

我通常使用file.replace函数在整个文本文件中更改具有一定数量的NaN.
现在,我只想在文本文件的第一行而不是整个文本中用一定数量的NaN代替.
您能给我提示这个问题吗?

I usually have used file.replace function for change NaNs with a certain number through entire text file.
Now, I would like to replace NaNs with a certain number in only first line of text file, not whole text.
Would you give me a hint for this problem?

推荐答案

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

You can only read the whole file, call .replace() for the first line and write it to the new file.

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)

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

If your file isn't really big, you can use just .join():

with open('out.txt', 'w') as fout:
    fout.write(''.join(lines))

如果它真的很大,您最好同时读取和写入行.

And if it is really big, you would probably better read and write lines simultaneously.

这篇关于仅在文本文件的第一行中替换某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆