Python處理文字換行符

2021-09-22 02:28:54 字數 1393 閱讀 9207

原始檔內容如下:

原始檔每行後面都有回車,所以用下面輸出時,中間會多了一行

>>> try:

with open(r"c:\users\administrator\desktop\20190506biji0.txt" ) as f :

for line in f:

print(line)

except filenotfounderror:

print("讀取檔案出錯")

hello world

how are you?

i am fine

有兩種方法處理:

1.print後面帶 end=』』,表示不換行

>>> try:

with open(r"c:\users\administrator\desktop\20190506biji0.txt" ) as f :

for line in f:

print(line,end='')

except filenotfounderror:

print("讀取檔案出錯")

hello world

how are you?

i am fine

2.用strip()函式去掉每一行的換行符

>>> try:

with open(r"c:\users\administrator\desktop\20190506biji0.txt" ) as f :

for line in f:

line=line.strip('\n')

print(line)

except filenotfounderror:

print("讀取檔案出錯")

hello world

how are you?

i am fine

再者:

>>> x='''hello world

how are you?

i am fine'''

>>> x.strip('\n')

'hello world\nhow are you?\ni am fine'

>>> print(x,end='')

hello world

how are you?

i am fine

>>> print(x)

hello world

how are you?

i am fine

參考:

Python處理文字換行符

原始檔每行後面都有回車,所以用下面輸出時,中間會多了一行 try with open f hjt.txt as f for line in f print line except filenotfounderror print 讀取檔案出錯 有兩種方法處理 1.print後面帶 end 表示不換行 ...

Python 換行符轉換

因為工作需求,需要把目錄下的所有換行符轉換為windows換行符 r n 檔案太多,只好寫乙個簡單的python指令碼轉換。import os import os.path rootdir r d src def replace filename try oldfile open rootdir f...

CSS學習(十二) 文字換行符

一 理論 1.word wrap a.normal 在半形空格或連字元的地方進行換行 b.break word 不截斷英文單詞換行 2.word break a.normal 中文到邊界上的漢字換行,英文從整個單詞換行 b.break all 強行截斷英文單詞換行 c.keep all 不允許字斷開...