我此时遇到的问题(对Python不熟悉)是将字符串写入文本文件。我遇到的问题是,字符串之间没有换行符,或者每个字符后都有换行符。代码如下:
import string, io
FileName = input("Arb file name (.txt): ")
MyFile = open(FileName, 'r')
TempFile = open('TempFile.txt', 'w', encoding='UTF-8')
for m_line in MyFile:
m_line = m_line.strip()
m_line = m_line.split(": ", 1)
if len(m_line) > 1:
del m_line[0]
#print(m_line)
MyString = str(m_line)
MyString = MyString.strip("'[]")
TempFile.write(MyString)
MyFile.close()
TempFile.close()
我的输入如下:
1 Jargon
2 Python
3 Yada Yada
4 Stuck
我这样做时的输出是:
JargonPythonYada YadaStuck
然后我将源代码修改为:
import string, io
FileName = input("Arb File Name (.txt): ")
MyFile = open(FileName, 'r')
TempFile = open('TempFile.txt', 'w', encoding='UTF-8')
for m_line in MyFile:
m_line = m_line.strip()
m_line = m_line.split(": ", 1)
if len(m_line) > 1:
del m_line[0]
#print(m_line)
MyString = str(m_line)
MyString = MyString.strip("'[]")
#print(MyString)
TempFile.write('\n'.join(MyString))
MyFile.close()
TempFile.close()
相同的输入,我的输出如下:
J
a
r
g
o
nP
y
t
h
o
nY
a
d
a
Y
a
d
aS
t
u
c
k
理想情况下,我希望每个单词都出现在单独的行上,而不是前面的数字。
谢谢,
MarleyH
答案 0 :(得分:2)
您必须在每行之后写'\n'
,因为您正在剥离原始'\n'
;
您使用'\n'.join()
的想法不起作用,因为它将使用\n
来加入字符串,将其插入字符串的每个字符串之间。相反,您需要在每个名称后面加一个\n
。
import string, io
FileName = input("Arb file name (.txt): ")
with open(FileName, 'r') as MyFile:
with open('TempFile.txt', 'w', encoding='UTF-8') as TempFile:
for line in MyFile:
line = line.strip().split(": ", 1)
TempFile.write(line[1] + '\n')
答案 1 :(得分:1)
fileName = input("Arb file name (.txt): ")
tempName = 'TempFile.txt'
with open(fileName) as inf, open(tempName, 'w', encoding='UTF-8') as outf:
for line in inf:
line = line.strip().split(": ", 1)[-1]
#print(line)
outf.write(line + '\n')
问题:
str.split()的结果是一个列表(这就是为什么,当你把它转换为str时,你得到['我的项目'])。
写入不添加换行符;如果你想要一个,你必须明确添加它。