Replace certain element in only first line of the text file

坚强是说给别人听的谎言 提交于 2020-01-24 00:14:06

问题


Thank you for your interest on my maybe silly question.

I have a text file and would like to replace certain elements which is "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?


回答1:


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)

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.




回答2:


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.

with open('your_file.txt', 'rw') 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.



来源:https://stackoverflow.com/questions/15468992/replace-certain-element-in-only-first-line-of-the-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!