[英]Reading a file and replacing LF, but not CR-LF with python
I work on Windows and have a bunch of text files where some lines end with CRLF and some end with LF.我在 Windows 上工作,有一堆文本文件,其中一些行以 CRLF 结尾,一些行以 LF 结尾。 What I need to do is to replace the ones that end with LF with
<br>
and leave CRLF as they are.我需要做的是用
<br>
替换以 LF 结尾的那些,并保持 CRLF 不变。
I tried regex (?<!\\\\r)\\\\n
, strip() and splitlines(), but python always treats LF the same as CRLF.我尝试过正则表达式
(?<!\\\\r)\\\\n
、strip() 和 splitlines(),但 python 总是将 LF 视为 CRLF。
What could I do to acomplish replace of only LF?我能做些什么来完成只替换 LF?
Thanks B.谢谢 B。
UPDATE更新
I checked your suggestions again, however they give me the same resulta as I mentioned - CRLF is treated the same as LF.我再次检查了您的建议,但是它们给了我与我提到的相同的结果 - CRLF 的处理方式与 LF 相同。
Im attaching the code I use alongside sample input file and the image of result I get.我附上了我使用的代码以及示例输入文件和我得到的结果图像。
with open(fileImport) as fp:
testContent = fp.read()
print("**** RESULT 1")
print(testContent)
print(" ")
print("**** RESULT 2")
testContent1 = re.sub(r'(?<!\r)\n', ' <br>', testContent)
print(testContent1)
print(" ")
print("**** RESULT 3")
testContent2 = testContent.replace("\n", "<br>")
print(testContent2)
This is what I get using different options...这就是我使用不同选项得到的结果......
**** RESULT 1
----Row1;TX2829;Text Object;Value1
----Row2;TX2756;Text Object;"= 'Value in row 1: ' &
Num(
Sum(A)/
Sum(B)
, '#.##0 EUR')"
----Row3;CH246;Pivot Table;Title of pivot
**** RESULT 2
----Row1;TX2829;Text Object;Value1 <br>----Row2;TX2756;Text Object;"= 'Value in row 1: ' & <br>Num( <br>Sum(A)/ <br>Sum(B) <br> <br> <br>, '#.##0 EUR')" <br>----Row3;CH246;Pivot Table;Title of pivot <br>
**** RESULT 3
----Row1;TX2829;Text Object;Value1<br>----Row2;TX2756;Text Object;"= 'Value in row 1: ' &<br>Num(<br>Sum(A)/<br>Sum(B)<br><br> <br>, '#.##0 EUR')"<br>----Row3;CH246;Pivot Table;Title of pivot<br>
This is what i need这就是我需要的
----Row1;TX2829;Text Object;Value1
----Row2;TX2756;Text Object;"= 'Value in row 1: ' &<br>Num(<br>Sum(A)/<br>Sum(B)<br><br> <br>, '#.##0 EUR')"
----Row3;CH246;Pivot Table;Title of pivot
Sample file is available at: https://www.dropbox.com/s/s81dibm8gxsfotf/TEST_FILE.csv?dl=0示例文件位于: https : //www.dropbox.com/s/s81dibm8gxsfotf/TEST_FILE.csv?dl=0
Thanks in advace, B预先感谢,B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.