簡體   English   中英

僅替換文本文件第一行中的某些元素

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

我有一個文本文件,想替換某些“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', '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))

這在任何長度的文件上都會很快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM