我有一个文本文件,其行如下:text1:numbers:text2
。如何将这些分开,以便我可以将text1:text2:numbers
输出到另一个文件?
file1=open("textfile.txt","r")
file2=open("textfile2.txt","w")
while True:
line=file1.readline()
a=line.split(":")
if line=="":break
答案 0 :(得分:0)
您可以将每个文本部分分配到split
中的变量,然后以单独的顺序写出。
with open("textfile.txt") as f1, open("textfile2.txt", "w") as f2:
for line in f1:
text1, numbers, text2 = line.split(":")
# N.B. this will fail if there are more *or* less than 3 parts to line.split(":")
# on any line of the file. Ensure that there is not, or wrap this in a
# try/except block and handle appropriately.
f2.write("{}:{}:{}\n".format(text1, text2, numbers))
# or f2.write(':'.join([text1, text2, numbers, "\n"]))
# or f2.write(text1 + ":" + text2 + ":" + numbers + "\n")
# or any other way to assemble the text you want.
# my favorite in Py3.6+ is an f-string
# f2.write(f"{text1}:{text2}:{numbers}\n")
请注意,我还使用上下文管理器打开文件,直接迭代文件对象而不是无限循环,直到readline
没有返回任何内容。您应该优先选择上下文管理器而不是显式open
和close
语句,因为它确保文件对象在退出块后关闭,即使该出口不是干净的(抛出和处理异常)或等)。迭代文件对象而不是在无限循环中一次读取一行只是惯用的更好看。