Python的file.write()方法与字符串处理问题
我现在遇到的问题是(因为我刚开始学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
2 个回答
2
你需要在每一行后面加上'\n'
,因为你已经去掉了原来的'\n'
;你想用'\n'.join()
的方法不行,因为这个方法会用\n
把字符串中的每个字符连接起来,也就是说它会在每个字符之间插入\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
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()后,得到的是一个列表(这就是为什么当你把它转换成字符串时,会得到['my item'])。
write方法不会自动添加换行符;如果你想要换行,必须自己手动加上。