【问题标题】:How can I read files with similar names on python and then work with them? [duplicate]如何在 python 上读取具有相似名称的文件然后使用它们? [复制]
【发布时间】:2019-07-16 08:18:51
【问题描述】:

所以我在一个项目中工作,我需要读取一堆文件,除了一个数字外,它们具有相同的名称,例如:

thing1.txt
thing2.txt
thing3.txt

然后我必须与他们合作,给他们取另一个名字:

example1='.\path\thing1.txt'

有什么方法可以让代码读取我这些区分数字的文件,然后以编号的形式将它们分配给新名称?

import fnmatch

for filename in os.listdir('.'):
    if fnmatch.fnmatch(filename, 'thing*.txt'):
        print(filename)

使用我现在使用的代码,我可以读取具有相同名称和不同编号的文件,但我无法在循环中重命名它们以在之后使用它们。

我想要一个类似循环的东西:

example*=thing*

其中 * 应该是数字。

编辑:我应该这么说的,但是我使用的文件 (thing1/2/3) 具有我需要在代码后面的某些操作中使用的数值,所以这就是我需要“重命名”它们的原因.

【问题讨论】:

  • rename them 是什么意思?你想要一些像{example1: thing1, example2: thing2, example3: thing3} 这样的字典,还是要将文件thing1.txt 重命名为some_other_thing1.txt
  • 所以我使用的文件(thing1.txt)是数值,所以我需要重命名它们以便能够将它们用于某些操作。
  • 抱歉@novich,我仍然没有得到你想要重命名的内容。
  • 所以,这些文件是我从另一个程序获得的输出,然后我需要在这段代码中使用它们作为输入,因为我将有很多这些 .txt 文件我想将它们重命名为我不想像'./path/etc'那样使用它们。
  • 现在明白了,谢谢。没有帮助任何答案?

标签: python python-3.x text


【解决方案1】:

尝试使用 os.walk().os.walk

for (root,dirs,files) in os.walk(main_folder): 
#iterate over all the files in the folders and sub folders
    for file in files:
         filepath = os.path.join(root,file)
         # read the file from thing and write the file in example
         with open(filepath ) as f:
              with open(filepath.replace('thing',example),'w') as g:
                      g.write(f)

【讨论】:

    【解决方案2】:

    您可以在 Python 3 中使用格式化文本。

    for i in range(10):
        txt = f'text{i}.txt'
        print(txt)
    

    【讨论】:

      【解决方案3】:

      您可以通过使用字符串格式来动态创建和执行 Python,以实际编写新的 Python 文件,然后从现有脚本中将其作为新进程执行。这将让您真正按照您的要求动态分配变量名称。

      真的,你可能应该把它们放在字典里:

      import os
      import fnmatch
      
      examples = {}
      
      for filename in os.listdir('.'):
          if fnmatch.fnmatch(filename, 'thing*.txt'):
              examples[filename[:6]] = filename
      
      

      输出:

      examples
      {'thing1': 'thing1.txt', 'thing2': 'thing2.txt', 'thing3': 'thing3.txt'}
      

      【讨论】:

        【解决方案4】:

        您可以使用字符串变量和 for 循环进行迭代:

        for n in range(1, 5):
            filename="file" + str(n) + ".csv"
            print (filename)
        

        要重命名文件,您可以使用 os 模块

        import os
        
        os.rename('file.txt', 'newfile.txt')
        

        【讨论】:

          【解决方案5】:

          要查找文件名中的数字,您可以这样做:

          fname = "some_filename1.txt"
          number = "".join(x for x in fname if x.isdigit())
          # This would, however, use any digits found in the filename as the number, so you can perhaps do something like:
          import os
          # The following code will find the number of file that is at the end of its name only
          fnameonly, ext = os.path.splitext(fname)
          if not fnameonly:
              fnameonly = ext # Fiilenames beginning with extension separator
              ext = ""
          fnameonly = fnameonly.rstrip()
          number = []
          for x in range(len(fnameonly)-1, -1, -1):
              if not fnameonly[x].isdigit(): break
              number.append(fnameonly[x])
          number.reverse()
          number = "".join(number)
          # In both cases, if number is empty, then the filename does not contain any numbers in it and you can skip this file
          # So, after you find the number:
          newfname = "Example %s%s" % (number, ext)
          try:
              os.rename(fname, newfname)
          except Exception, e:
              print "Error: couldn't rename the file '%s' to '%s' because:\n%s\nRenaming skipped" % (fname, newfname, str(e))
          

          现在,上面的代码可能看起来有点太多了。不过,您也可以使用正则表达式来做到这一点。 (如果你知道如何:D) 或上述代码的任意数量的变体。将它放在一个函数中,然后使用它遍历文件夹来重命名文件。 我提供的代码比使用例如灵活得多。格式化。它可用于任何扩展名的文件,并确保您得到的是真正的数字,而不是某些添加文本的一部分,例如:带有格式化解决方案的“thingy1.txt”将导致“exampley1.txt”,其中你不想发生。所以,要么使用我的代码,要么使用正则表达式。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-12-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-25
            • 1970-01-01
            相关资源
            最近更新 更多