簡體   English   中英

Python 可以使用 \n 從文件中讀取行並將其打印為 2 行嗎?

[英]Can Python read line from file with \n and print it in 2 lines?

在此處輸入圖像描述 我制作了我寫的文本文件:

我的名字\n是

在代碼中:

with open(file.txt) as f:
    for line in f:
        print(line)

output:

我的名字\n是

我期望:

我的名字

有沒有辦法用 \n 制作文本文件並在程序中使用分隔成幾行的字符串?

試試這個它應該工作

with open('file.txt') as f:
    data = f.read().split('\\n')
    for d in data:
        print(d)

在這里,我只是簡單地讀取整個文件,然后將其拆分為“\n”列表。

python 中的字符串變量需要一種方法來知道“新行”應該在哪里。

\n是一個換行信號(按回車時產生)

\\n是原始文本,當你想寫 \n 並且不執行斷行時很有用。 (讓它寫成'\n')

因此,您需要將 map '\\n' 替換為 '\n'。

解決方案:

with open('file.txt') as f:
    Temp=f.read().replace('\\n','\n') # Declare Temp variable is not necesary
    print(Temp)

# Without Temp
with open('file.txt') as f:
    print(f.read().replace('\\n','\n'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM