简体   繁体   中英

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

So I'm working in a project where I need to read a bunch of files, and they have the same name except for a number, something like:

thing1.txt
thing2.txt
thing3.txt

Then I have to work with them giving them another name:

example1='.\path\thing1.txt'

Is there any way that the code can read me these files differentiating between the numbers and then assign them to that new name in a numbered form?

import fnmatch

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

With the code I'm using right now I can read the files with the same name and different number, but I can't rename them in a loop to work with them after.

I want something like a loop that does this:

example*=thing*

Where * should be the number.

Edit: I should have said so, but the files I work with (thing1/2/3) have numerical values that I need to use in some operations later in the code, so that's why I need to 'rename' them.

You can use formatted text in Python 3.

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

try using 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)

You can dynamically create and execute Python by using string formatting to actually write a new python file, and then execute it as a new process from your existing script. That would let you actually assign variable names dynamically as you're asking.

Really though, you should probably just put them in a dictionary:

import os
import fnmatch

examples = {}

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

output:

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

You could use a string variable and a for loop to iterate:

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

To rename a file you can use os module

import os

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

To find the number inside a filename you can do:

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))

Now, the above code might seem as a little too much. You can use regular expressions to do it as well though. (if you know how :D ) Or any number of variants of above code(s). Put it in a function and then iterate over the folder using it to rename files. The code I provided is much more flexible than using eg formatting. It is usable on a file of any extension and it makes sure that what you are getting is really the number and not a part of some added text like: "thingy1.txt" with formatting solution would result in "exampley1.txt", which you do not want to happen. So, either use my code or regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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