【问题标题】:How to separate different text files based on the file number如何根据文件编号分隔不同的文本文件
【发布时间】:2019-09-24 19:42:17
【问题描述】:

我在一个文件夹中有 20 个文本文件。文件名表示为

a 1.txt,a 2.txt,a 3.txt...

有些文件有不同的操作,有些则不同

我已将文件编号传递给list lst_num=[1,6,15,16],像这样都需要写入一个文件,不在列表中的文件应该写入另一个文件

for file in fnames:
    nume=os.path.splitext(file)[0].split()[1]
    lst_num=[1,6,15,16]
    fp = open(file, 'r').read()
    for i in lst_num:
        if file=="a "+str(i)+".html":
            print(file)
        else: 
            print('--'+file)

列表中的所有文件都传递给一个文本文件 不在另一个文件的列表中

【问题讨论】:

  • 你想分离文件,还是连接它们?
  • 文件名是1.txt还是a 1.txt
  • 只是我需要在这里分离文件
  • 是“1.txt”
  • file== "a 1.html"*.txt,你为什么要比较它?

标签: python python-3.x text-processing


【解决方案1】:

您当前的代码与html 文件进行比较,但您的文件扩展名实际上是txt
此外,您的双 for 循环最终会多次打印相同的文件名

您实际上不需要遍历文件和lst_num
只需使用lst_num 创建文件名以写入一个文件,然后通过获取所有文件和lst_num 文件之间的差异来获取要写入另一个文件的文件名

fnames = ['a 1.txt', 'a 2.txt'....]
lst_num=[1,6,15,16]

#All files in lst_num
in_list_files = ['a {}.txt'.format(item) for item in lst_num]

#All files outside lst_num
not_in_list_files = list(set(fnames) - set(in_list_files))

print(in_list_files)
print(not_in_list_files)

输出将是

['a 1.txt', 'a 6.txt', 'a 15.txt', 'a 16.txt']
['a 2.txt', 'a 3.txt', 'a 4.txt', ....]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    相关资源
    最近更新 更多