我有一个文本文件,我正在逐行阅读并将每个文本文件分配给一个变量,但有些行我想用新行打印,这样我就可以格式化它们一点。文本文件看起来像这样:
Projectinfo.txt
Greeting: Hello,
How are you?
Farewell: Goodbye
代码:
newlinetxt.py
txtfile = 'ProjectInfo.txt' #Open the txt file
with open(txtfile, encoding="utf8") as file:
content = file.readlines()
line1 = content[0]
line2 = content[1]
start = 'Greeting: '
end = 'Farewell: '
a = line1
Hellomsg = (a[a.find(start)+len(start):a.rfind(end)])
start = 'Farewell: '
end = ''
b = line2
Byemsg = (b[b.find(start)+len(start):b.rfind(end)])
print(Hellomsg)
print(Byemsg)
Hello
you?
当我打印出来的时候,它只打印第一个变量'Hellomsg'
的第一行,然后第二行被分配给第二个变量'Byemsg'
,而不是它自己的变量"Farewell"
不加换行符,输出:
Hello, How are you?
Goodbye
但是我想:
Hello,
How are you?
Goodbye
我也试过在。txt文件中使用"Hello, n How are you?"
,但它会用n打印字符串,而不是实际创建一个新行。
import re
Hellomsg = re.sub("\\n", 'n', a)
n
是一个不可见的字符,在文本编辑器中输入它的唯一方法是按"Enter"按钮。使用这么多反斜杠的原因是,当python读取"n"在您的文本文件中,它在第一个反斜杠之前添加一个反斜杠,以表示反斜杠是文字。当对它进行搜索时,需要找到2个字面反斜杠,这意味着两个反斜杠各需要一个反斜杠。
如果你的实际问题比你的玩具更复杂,你需要调整"\\n"
,这样你就不会用换行符替换反斜杠'n'之类的东西。