我有一个文本文件,想替换某些元素为“ NaN”。
我通常使用file.replace
函数通过整个文本文件更改具有一定数量的NaN。现在,我只想在文本文件的第一行而不是整个文本中用一定数量的NaN代替。您能给我这个问题的提示吗?
您只能读取整个文件,在第一行中调用.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)
如果文件不是很大,则可以只使用.join():
with open('out.txt', 'w') as fout:
fout.write(''.join(lines))
如果它真的很大,您最好同时读取和写入行。
只要您接受一些约束,就可以破解。替换字符串的长度必须与原始字符串的长度相等。如果替换字符串比原始字符串短,请用空格填充较短的字符串以使其长度相等(这仅在数据中多余的空格可接受的情况下有效)。如果替换字符串比原始字符串长,则无法就地替换,需要遵循Harold的回答。
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))
这对任何长度的文件都会很快。