问题描述
我有一个包含大约1500个excel文件的文件夹。 每个文件的格式如下:
- 0d20170101abcd.xlsx
- 1d20170101ef.xlsx
- 0d20170104g.xlsx
- 0d20170109hijkl.xlsx
- 1d20170109mno.xlsx
- 0d20170110pqr.xlsx
文件名的第一个字符是“0”或“1”,后跟“d”,后跟创建文件的日期,后跟客户ID(abcd,ef,g,hijkl,mno,pqr)。 id没有固定的长度,它可以变化。
我想为每个唯一日期创建文件夹(文件夹名称应为日期),并将具有相同日期的文件移动到单个文件夹中。 因此,对于上面的示例,必须创建4个文件夹(20170101,20170104,20170109,20170110),并将具有相同日期的文件复制到其各自的文件夹中。
我想知道在python中是否有任何方法可以做到这一点? 很抱歉没有发布任何示例代码,因为我不知道如何开始。
1楼
试试这个:
import os
import re
root_path = 'test'
def main():
# Keep track of directories already created
created_dirs = []
# Go through all stuff in the directory
file_names = os.listdir(root_path)
for file_name in file_names:
process_file(file_name, created_dirs)
def process_file(file_name, created_dirs):
file_path = os.path.join(root_path, file_name)
# Check if it's not itself a directory - safe guard
if os.path.isfile(file_path):
file_date, user_id, file_ext = get_file_info(file_name)
# Check we could parse the infos of the file
if file_date is not None \
and user_id is not None \
and file_ext is not None:
# Make sure we haven't already created the directory
if file_date not in created_dirs:
create_dir(file_date)
created_dirs.append(file_date)
# Move the file and rename it
os.rename(
file_path,
os.path.join(root_path, file_date, '{}.{}'.format(user_id, file_ext)))
print file_date, user_id
def create_dir(dir_name):
dir_path = os.path.join(root_path, dir_name)
if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
os.mkdir(dir_path)
def get_file_info(file_name):
match = re.search(r'[01]d(\d{8})([\w+-]+)\.(\w+)', file_name)
if match:
return match.group(1), match.group(2), match.group(3)
return None, None, None
if __name__ == '__main__':
main()
请注意,根据文件的名称,您可能希望更改(将来)我使用的正则表达式,即[01]d(\\d{8})([\\w+-]+)
(您可以使用它,看看有关如何阅读详细信息)...
2楼
检查此代码。
import os
files = list(x for x in os.listdir('.') if x.is_file())
for i in files:
d = i[2:10] #get data from filename
n = i[10:] #get new filename
if os.path.isdir(i[2:10]):
os.rename(os.getcwd()+i,os.getcwd()+d+"/"+i)
else:
os.mkdir(os.getcwd()+i)
os.rename(os.getcwd()+i,os.getcwd()+d+"/"+i)
这是repl
3楼
试试这个:
import os, shutil
filepath = "your_file_path"
files = list(x for x in os.listdir(filepath) if x.endswith(".xlsx"))
dates = list(set(x[2:10] for x in files))
for j in dates:
os.makedirs(filepath + j)
for i in files:
cid = i[10:]
for j in dates:
if j in i:
os.rename(filepath+i,cid)
shutil.copy2(filepath+cid, filepath+j)