【问题标题】:How to print the filename with respect to content inside in python如何在python中打印关于内容的文件名
【发布时间】:2019-08-11 07:00:14
【问题描述】:

我有 2 个文件 a.txtb.txt

a.txt 包含带有 2 个空行的文本“T Mobile Rider”。 b.txt 包含 2 个空行,后跟文本“Iphone”。

代码

import os
for (dirname,dirs,files) in os.walk('.'):
for filename in files:
    if filename.endswith('.txt'):
        thefile = os.path.join(dirname,filename)
        size =  (os.path.getsize(thefile),thefile)
        if size[0] == 22 or size[0] == 23:
            print ('T-Mobile:',thefile)
            continue
        fhand = open(thefile,'r')
        lines = list()
        for line in fhand:
            lines.append(line)
            #print (lines)
        fhand.close()
        if len(lines) == 3 and lines[2].startswith('Iphone'):
            print ('iPhone:', thefile)
            continue

我的输出

T-Mobile: .\Captures\a.txt
T-Mobile: .\Captures\b.txt

期望的输出

T-Mobile: .\Captures\a.txt
iPhone: .\Captures\b.txt   

【问题讨论】:

  • 问题不是很清楚。请张贴文本文件的内容。另外,我在代码中看到了很多幻数和硬代码,说实话看起来不太合乎逻辑。
  • 不相关:只做lines = list(fhand) 而不是你的循环

标签: python file file-io os.walk


【解决方案1】:

我已经按照以下逻辑打印了文件名:

  • iPhone: FILENAME 如果文件在任何行中包含 Iphone
  • T-Mobile: FILENAME 如果文件在任何行中包含 T Mobile

文件夹结构:

├── Captures
│   ├── a.txt
│   └── b.txt
└── code.py

代码:

import os
for dirname, dirs, files in os.walk('.'):
    for filename in files:
        if filename.endswith('.txt'):
            thefile = os.path.join(dirname, filename)
            with open(thefile) as f:
                lines = f.readlines()
                if any('Iphone' in line for line in lines):
                    print('iPhone:', thefile)
                if any('T Mobile' in line for line in lines):
                    print('T-Mobile:', thefile)

输出:

T-Mobile: ./Captures/a.txt
iPhone: ./Captures/b.txt

【讨论】:

    【解决方案2】:

    我想我在我的电脑上重新创建了您的案例,并找到了您可能想要的一种解决方案:

    import os
    import re
    
    for (dirname, dirs, files) in os.walk('.'):
        for filename in files:
            if filename.endswith('.txt'):
                thefile = os.path.join(dirname, filename)
                with open(thefile, 'r') as fhand:  # open the file using with formula is preferred
                    # this block is for classifying the files
                    for line in fhand:
                        if re.match('t[ .-]?mobile', line.lower()):
                            print('T-Mobile: ', thefile)
                            break
                        elif re.match('iphone', line.lower()):
                            print('iPhone: ', thefile)
                            break
    
    

    请注意,我使用re module 更改了文件的分类方式。通过您提供的示例,我相信这些实际上会更好。在这里,我打开找到的每个“.txt”文件并逐行读取,试图找到告诉它属于哪个组的模式(这里只有两个 - T-Mobile 和 iPhone,但也许你想定义更多) .文件只能归为一组,所以一旦找到满足条件的行,就关闭文件并打印相应的信息。


    我提供的条件远没有你那么严格,因此它们可能无法涵盖所有​​内容,从而产生误报结果。例如,如果您有一些文件以“Iphone”开头的第一行,它将被归类到 iPhone 组。如果由于某种原因您只想匹配在第三行中包含此单词的这些文件,那么在负责对文件进行分类而不是遍历行的块中,您可以使用 fhand.readlines() 一次读取它们并应用指定行的条件。

    我稍微改变逻辑的原因是使用难以理解的硬编码条件是一种不好的做法。此外,这些对于任何更改都非常脆弱,并且如果发生任何事情都需要进行大量修改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 2021-08-02
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      相关资源
      最近更新 更多