到目前为止,我有以下内容:
source_folder = 'file_location'
for file in os.listdir(source_folder):
if file.startswith('stnet_'):
os.rename(file, file.replace('stnet_a_b', '%s_' % time.ctime(os.path.getctime(file)) + 'stnet_a_b'))
问题是我一直得到FileNotFoundError:[WinError 2]系统找不到指定的文件'stnet_a_b.raw'
有人可以指出我做错了吗?
谢谢。
os.listdir
只能获取没有目录的文件名,而os.rename
,os.path.getctime
需要带有目录的全名(如果当前目录不是精确的file_location,那么将找不到该文件)。您可以使用os.path.join
获取全名。如果您使用的是Windows,则必须确保文件名不包含代码所包含的特殊字符。
dir = r'file_location'
# os.chdir(dir) # in case you don't want to use os.path.join
for filename in os.listdir(dir):
print(filename)
if filename.startswith('stnet_'):
src = os.path.join(dir, filename)
ctime_str = str(time.ctime(os.path.getctime(src)))
ctime_str = ctime_str.replace(':', '').replace(' ', '') # remove special characters
fn_new = filename.replace('stnet_a_b',
'{}_'.format(ctime_str + 'stnet_a_b'))
des = os.path.join(dir, fn_new)
print('src={}, des={}'.format(src, des))
os.rename(src, des)
请尝试以上代码。