我正在嘗試從如下所示的檔案中讀取一些字串:
123456
password
12345678
qwerty
123456789
12345
1234
111111
1234567
dragon
...till the end
我想將每一行列印到一個檔案中,并以下列方式插入引號和逗號,
"123456",
"password",
"12345678",
...till the end
我試過:
fhand = open("pass.txt")
for line in fhand:
print(f'"{line}",',end="")
但是,此代碼在錯誤的位置列印引號和逗號:
"123456
","password
","12345678
","qwerty
...till the end
如何洗掉這些虛假的換行符?
uj5u.com熱心網友回復:
兩件事情:
當您第一次讀入時,每一行都包含一個尾隨換行符。使用:
line.rstrip()而不是
line格式字串。與您詢問的問題無關,但值得指出:您應該在回圈
fhand.close()之后使用關閉檔案句柄。for更好的是,改用背景關系管理器,它會自動為您關閉檔案句柄:with open("pass.txt") as fhand: for line in fhand: print(f'"{line.rstrip()}",',end="")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461362.html
標籤:Python python-3.x 细绳 文件 解析
上一篇:如何使用Date.ParseStrategy在Swift5.6中將字串決議為日期?
下一篇:從CSV到Java中的XML
