当 Python 3 中并非所有项目都被分隔时,如何拆分列表中的分隔字符串?

How do I split delimited strings in a list when not all items are delimited in Python 3?

我在文本文件中有一列字符串 w/o a header (test_in.txt):

apple 
orange
banana
grape;pear;plum
cherry
pineapple

我想阅读的内容:

apple
orange
banana
grape
pear
plum
cherry
pineapple

我正在使用以下代码:

with open("test_out.txt", "wt") as outfile:
with open("test_in.txt", "rt") as infile:
    for line in infile:
        line.split(";")
        outfile.write(line)

似乎无法正常工作。我也试过 "if" 语句,但我肯定遗漏了一些东西。

如有任何帮助,我们将不胜感激!

line.split(";") returns 你这一行的不同单词,它不会原地修改line,所以你需要写每个返回的单词:

for word in line.split(";"):
    outfile.write(word)

或者,您只需将所有 ; 个字符替换为 \n,例如:

outfile.write(infile.read().replace(';', '\n'))