Python 3ファイルの一括作成、ファイル名の変更、ロールバック操作
1960 ワード
まず、運転操作を見てみましょう.
ソースコードを見てみましょう.
root@cat:~/coding# python3 mass_change.py
input the folder you want to change:txt
txt
3.txt
4.txt
1.txt
2.txt
5.txt
root@cat:~/coding# ls txt
[vale]-1.txt [vale]-2.txt [vale]-3.txt [vale]-4.txt [vale]-5.txt
root@cat:~/coding# python3 roll_back.py
Enter the folder yout want to roll back:
txt
[vale]-5.txt
[vale]-1.txt
[vale]-4.txt
[vale]-2.txt
[vale]-3.txt
********************
[vale]-5.txt
5.txt
[vale]-1.txt
1.txt
[vale]-4.txt
4.txt
[vale]-2.txt
2.txt
[vale]-3.txt
3.txt
root@cat:~/coding# ls txt
1.txt 2.txt 3.txt 4.txt 5.txt
ソースコードを見てみましょう.
# hello , 1-5
# Linux {1..5}.txt txt
for i in range(1,6):
file = i
f = open(str(file) + ".txt","w")
f.write("hello")
f.close()
# [vale]-
import os
foldername = input("input the folder you want to change:")
print(foldername)
#get_folder_file
file_names = os.listdir(foldername)
os.chdir(foldername)
#change_name
for name in file_names:
print(name)
os.rename(name,"[vale]-" + name)
#!/usr/bin/env python
# , [vale]-
import os #
# ,
changed_folder = input("Enter the folder yout want to roll back:
\t\t
")
#
os.chdir(changed_folder)
#
os.getcwd()
path = os.getcwd()
#
dirs = os.listdir(path)
for dir in dirs:
print(dir)
print("*" * 20) #
#
for dir in dirs:
old_filename = dir #
print(old_filename) # , ( )
new_filename = old_filename.replace("[vale]-","")
# replace ,( , )
print(new_filename)
os.rename(old_filename,new_filename) #
# , , ,