【问题标题】:Split and print the word before and after the \ of *n of lines, from a txt to two different txt's拆分并打印 *n 行的 \ 前后的单词,从一个 txt 到两个不同的 txt
【发布时间】:2021-01-13 06:51:30
【问题描述】:

我搜索了一下,但找不到适合我需要的解决方案。 我是 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文件,没有任何错误。

非常感谢任何建议,提前感谢您能给我的任何帮助。

【问题讨论】:

  • 我已经检查过了,但就我而言,路径位于 txt 文件中,而不是路径本身。也许我不明白 os.path 是如何工作的。
  • os.path.basename(text) 应该只返回文件名

标签: python python-3.x file split txt


【解决方案1】:

您可以在字符串列表中读取文件并将每个字符串拆分以创建 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)

【讨论】:

  • 工作就像一个魅力,谢谢。一个问题:如果 [0] 返回第一个单词,[-1] 返回最后一个单词,1 会做什么?
  • n 表示第 (n+1) 个元素。所以 [1] 将返回第二个元素。在这种情况下,第二个是最后一个元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 2020-06-05
  • 2013-10-09
  • 2015-03-01
  • 1970-01-01
相关资源
最近更新 更多