繁体   English   中英

如何在python上读取具有相似名称的文件,然后使用它们?

[英]How can I read files with similar names on python and then work with them?

因此,我在一个需要读取一堆文件的项目中工作,这些文件除了数字之外都具有相同的名称,例如:

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)具有数值,以后在代码中的某些操作中需要使用这些数值,因此这就是为什么我需要“重命名”它们的原因。

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

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

尝试使用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)

您可以使用字符串格式来实际创建新的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'}

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

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

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

import os

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

要查找文件名中的数字,您可以执行以下操作:

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”,你不想发生。 因此,请使用我的代码或正则表达式。

暂无
暂无

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

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