繁体   English   中英

拆分并打印 *n 行的 \\ 前后的单词,从一个 txt 到两个不同的 txt

[英]Split and print the word before and after the \ of *n of lines, from a txt to two different txt's

我四处搜索了一下,但找不到适合我需求的解决方案。 我是python的新手,所以如果我问的很明显,我很抱歉。

我有一个 .txt 文件(为简单起见,我将其称为 inputfile.txt),其中包含一个文件夹\\文件名称列表,如下所示:

camisos\CROWDER_IMAG_1.mov
camisos\KS_HIGHENERGY.mov
camisos\KS_LOWENERGY.mov

我需要的是拆分第一个单词( \\之前的单词)并将其写入 txt 文件(为简单起见,我将其称为 outputfile.txt)。

然后取第二个( \\之后的那个)并将其写入另一个 txt 文件。

这是我到目前为止所做的:

 with open("inputfile.txt", "r") as f:
        lines = f.readlines()
    with open("outputfile.txt", "w") as new_f:
        for line in lines:
            text = input()
            print(text.split()[0])

在我看来,这应该只打印新 txt 中的第一个单词,但我只有一个空的 txt 文件,没有任何错误。

非常感谢任何建议,在此先感谢您能给我的任何帮助。

您可以在字符串列表中读取文件并将每个字符串拆分以创建 2 个单独的列表。

with open("inputfile.txt", "r") as f:
    lines = f.readlines()

X = []
Y = []

for line in lines:
    X.append(line.split('\\')[0] + '\n')
    Y.append(line.split('\\')[1])

with open("outputfile1.txt", "w") as f1:
    f1.writelines(X)

with open("outputfile2.txt", "w") as f2:
    f2.writelines(Y)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM