[英]Replacing \n while keeping \r\n intact
我有一個巨大的 CSV 文件(196244 行),其中除了新行之外還有 \n,我想刪除那些 \n 但保持 \r\n 完好無損。 我已經嘗試過line.replace
但似乎無法識別\r\n
所以接下來我嘗試了正則表達式
with open(filetoread, "r") as inf:
with open(filetowrite, "w") as fixed:
for line in inf:
line = re.sub("(?<!\r)\n", " ", line)
fixed.write(line)
但它並沒有保留\r\n
它正在刪除所有內容。 我不能在 Notepad++ 中執行此操作,它會在此文件上崩潰。
您沒有將換行符暴露給正則表達式引擎。 此外,當使用r
模式open
時,換行符被“規范化”為 LF,為了將它們全部保留在輸入中,您可以使用b
以二進制模式讀取文件。 然后,您還需要記住在正則表達式模式和替換中使用b
前綴。
您可以使用
with open(filetoread, "rb") as inf:
with open(filetowrite, "wb") as fixed:
fixed.write(re.sub(b"(?<!\r)\n", b" ", inf.read()))
現在,整個文件將被讀入單個字符串(使用inf.read()
)並且換行符將被匹配,並最終被替換。
關注
"rb"
"wb"
寫出文件re.sub(b"(?<,\r)\n", b" ". inf.read())
包含帶有字符串文字的b
前綴,並且inf.read()
將文件內容讀入單個變量。當您使用一個簡單的open()
調用打開一個文件時,它將通過TextIOWrapper
加載一個包含各種換行符的文件視圖,只需\n
顯式設置newline="\r\n"
應該允許您按照預期的方式讀寫換行符
with open(path_src, newline="\r\n") as fh_src:
with open(path_dest, "w", newline="\r\n") as fh_dest:
for line in fh_src: # file-likes are iterable by-lines
fh_dest.write(line[:-2].replace("\n", " "))
fh_dest.write("\r\n")
內容示例
>>> with open("test.data", "wb") as fh:
... fh.write(b"""foo\nbar\r\nbaz\r\n""")
...
14
>>> with open("test.data", newline="\r\n") as fh:
... for line in fh:
... print(repr(line))
...
'foo\nbar\r\n'
'baz\r\n'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.