In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use Python to move and rename 2000 files". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to move and rename 2000 files using Python.
I. description of requirements
To make the case described in this article more general-purpose, I created a new folder, files1, containing 1800 files, as shown below:
The contents that need to be completed are as follows:
Move 1835 files to the new folder file2 and rename the files, starting with the serial number and the word "final draft", such as changing the name to "1-final draft-xxxxx (original file name)"
You may think to yourself: this is what people do? But it's true that this is a real requirement, and batch renaming of files is very common, and it can only take a lot of time and manpower to do without some skills. The trick here is Python.
There is another question: do you want to move and then rename or rename and then move? Keep looking down!
II. Pre-knowledge and data preparation
1. Generate a large number of random files
There is no such need in a real office scene, after all, who wants to generate a lot of useless files for their computers for no reason (and don't misuse other people's computers).
It has to be mentioned that generating random files can help us better test our Python file management skills. If you don't have the right folders and folders to practice for yourself, why not write your own code to generate it?
Of course, in the process, we will also learn some knowledge points, first look at the code:
Import random import string for i in range (2000): random_str = '.join (random.sample (string.ascii_letters + string.digits, random.randint (1,11) file = open (r "C:\\ xxx\\ file1" + random_str + ".txt",' wicked') # the path before is the target folder file.write (''.join (random.sample (string.ascii_letters + string.digits, random.randint (1)) where the files are generated 11) file.close ()
You can get all the letters and numbers through string, and use random.sample () to routinely accept two parameters, one is the range of sampling, the other is the number of sampling, and the default is to put back sampling. In this way, 1-10 can be randomly selected in a given alphanumeric range, but the result returned is a list, and the string concatenation needs to be done with the .join method.
After the file is generated with a randomly generated name, something is randomly written inside it in a similar way:
The above writing is not elegant because you need to use file.close () release, and a better way is to directly use the context manager with structure to reduce the chance of error:
Import random import string for i in range (2000): random_str = '.join (random.sample (string.ascii_letters + string.digits, random.randint (1,11)) with open (r "C:\\ xxx\\ file1" + random_str + ".txt",' wicked') as file: file.write ('.join (random.sample (string.ascii_letters + string.digits, random.randint (1,11)
Because even if the names are randomly generated, the scope and frequency of the sampling are small, which determines that some of the names in the 2000 samples will be exactly the same, and the documents formed later will cover the files generated before. as a result, there are not 2000 files.
two。 Rename files / folders
You need to use the os.rename () method of the built-in library os:
Import os os.rename ('practice.txt',' practice_rename.txt') # rename file os.rename ('folder 1', 'folder 2') # rename folder
Although there is a need to rename files in the requirements, there is no need to rely directly on this method.
3. Move files / folders
You need to use the shutil.move method of the built-in library shutil:
Import shutil shutil.move (ringing.\ practice.txt', rushing.\ folder 1max') shutil.move (ringing.\ practice.txt', ringing.\ folder 1According to new.txt')
Notice the difference between the last two lines of code above? The first line moves the target file to the target folder, while the second line can rename the target file while moving it to the target folder.
In other words, we don't need to use os.rename to name the file and then use shutil.move to move it to the specified folder, but we can use shutil.move to get there in one step.
4. Traversing to get files
Adopt an iterative framework based on the glob library:
Import glob path = xxx for file in glob.glob (f'{path} / * * / * .xlsx', recursive=True): pass
The above code can get the Excel files (.xlsx format) under all folders within a given path. The recursive parameter defaults to False, which allows you to traverse step by step when it is True.
In this example, you need to get all the .txt files under a given folder, which is even simpler:
Import glob path = xxx for file in glob.glob (f'{path} / * .txt'): pass
Third, code implementation
In the previous section, we have broken down the requirements into small pieces and sorted out our ideas, and now we are ready to write code. First import the required libraries:
Import os import shutil import glob path = r "C:\ xxx" # the upper-level path of the folder path where a large number of files need to be renamed to move
As mentioned above, you don't need to take advantage of os.rename, so why import the os library?
On the one hand, it is necessary to generate new folders through this library. It can also be done manually, but it is not easy to make mistakes when given too much code:
If not os.path.exists (path + r'\ file2'): os.mkdir (path + r'\ file2')
On the other hand, the following will use it to get the file name, and then you can move and rename it in one step, and the glob iterative file framework traverses to get the absolute path of the file:
Count = 1 # generate sequence number for file in glob.glob (f'{path}\\ test\\ * .txt'): # here is the absolute path of the file, which can be directly replaced and modified by string method, but for ease of understanding, I still use the path to concatenate filename = os.path.basename (file) shutil.move (file, path + r'\ file2' + f'{count}-final-{filename}') count + = 1 to here. I believe you have a deeper understanding of "how to use Python to move and rename 2000 files". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.