简体   繁体   English

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

[英]Replace certain element in only first line of the text file

I have a text file and would like to replace certain elements which is "NaN".我有一个文本文件,想替换某些“NaN”元素。

I usually have used file.replace function for change NaNs with a certain number through entire text file.我通常使用file.replace函数在整个文本文件中更改具有特定数量的 NaN。
Now, I would like to replace NaNs with a certain number in only first line of text file, not whole text.现在,我想在文本文件的第一行而不是整个文本中用某个数字替换 NaN。
Would you give me a hint for this problem?你能给我一个关于这个问题的提示吗?

You can only read the whole file, call .replace() for the first line and write it to the new file.您只能读取整个文件,在第一行调用 .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)

If your file isn't really big, you can use just .join():如果你的文件不是很大,你可以只使用 .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.如果它真的很大,您可能会更好地同时读取和写入行。

You can hack this provided you accept a few constraints.只要您接受一些限制,您就可以破解它。 The replacement string needs to be of equal length to the original string.替换字符串需要与原始字符串等长。 If the replacement string is shorter than the original, pad the shorter string with spaces to make it of equal length (this only works if extra spaces in your data is acceptable).如果替换字符串比原始字符串短,请用空格填充较短的字符串以使其长度相等(这仅适用于数据中的额外空格可接受的情况)。 If the replacement string is longer than the original you can not do the replacement in place and need to follow Harold's answer.如果替换字符串比原始字符串长,则您无法就地替换,需要遵循 Harold 的回答。

with open('your_file.txt', 'r+') as f:
    line = next(f) # grab first line
    old = 'NaN'
    new = '0  ' # padded with spaces to make same length as old 
    f.seek(0) # move file pointer to beginning of file
    f.write(line.replace(old, new))

This will be fast on any length file.这在任何长度的文件上都会很快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM