python去掉txt檔案行尾換行

2021-10-17 03:03:36 字數 1494 閱讀 9097

誤區

例項

對於原始檔案

使用以下語句只是對讀出的內容刪除了行尾的換行符,而不是真正將修改的結果寫入到原始的檔案中。

'''

'''filename =

"./text.txt"

with

open

(filename,

'r')

as f:

print

("open ok"

)for line in f.readlines():

for a in line:

# print(a)

if a ==

'\n'

:print

("this is \\n"

) a =

" "for line in f.readlines():

for a in line:

if a ==

'\n'

:print

("this is \\r\\n"

)for line in f.readlines():

line = line.replace(

"\n"

," "

) line = line.strip(

"\n"

)"""open ok

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

this is \n

"""

但是原始檔案並沒有被修改

正確做法

將檔案中的讀取後,使用寫語句將修改後的內容重新寫入新的檔案中

with

open

('./text_1.txt'

,'w'

)as f:

with

open

('./text.txt'

,'r'

)as fp:

for line in fp:

line =

str(line)

.replace(

"\n"

," "

) f.write(line)

linux 檔案內容行尾去掉M

g m s ctrl v m ctrl m 1 vi批量替換檔案字元命令 2011 09 19 11 41 02 標籤 雜談 分類 工作 利用 s 命令可以實現字串的替換。具體的用法包括 s str1 str2 用字串 str2 替換行中首次出現的字串 str1 s str1 str2 g 用字串 ...

Python檔案複製(txt檔案)

功能 這個py指令碼是把乙個txt檔案 原始檔 複製到另乙個txt檔案 目的檔案 裡面 演算法思路 程式首先判斷原始檔 用exists函式判斷 和目的檔案是否存在,如果不存在則輸出檔案路徑不存在,如果存在則先把原始檔讀出來,再寫到目的檔案中去 coding utf 8 from sys import...

Python 讀取TXT檔案

一 開啟檔案 f open filename,access mode r buffering 1 filename 檔名 access mode 開啟方式,r讀,w寫,a追加,r w a 都是以讀寫方式開啟,rb二進位制讀,wb二進位制寫,rb wb ab 二進位制讀寫 buffering 預設值 ...