使用python为目录中的每个文件创建文本文件



我用auto热键创建了这个,但我无法组织它们

^p::
Loop,  filename*.png
{
SplitPath, A_LoopFileName,,,, name_no_ext
FileAppend, %name_no_ext%`n, filename%name_no_ext%.txt
}

所以我决定用python编写它,但我不能用oslib为每个文件名制作文本文件我不能从文本文件中的文件名中删除点或自定义布局

这是我的代码:

import os 
import io 
dir_path = 'user/to/my/path'
#first add incremental number to the file name
i = 1
for file in os.listdir(dir_path):
if file.endswith(".png"):
os.rename(file,'#' +'{0:02d}'.format(i) + file)
i+=1
#now add text file for each then write there names of the files
a = io.open("output.txt", "w", encoding="utf-8")
for path, subdirs, files in os.walk(dir_path):
for filename in files:
f = os.path.join(filename)
f = os.path.splitext(filename)[0]
f = f.replace('  ', 'n')
a.write(str(f) + "n")  

文件名如下:

Angel    .Ghoul   .Angry    .black & waite     .Cannon Pink    ..png

和该脚本的输出,而不重命名增量编号:

Angel
.Ghoul
.Angry
.black & waite
.Cannon Pink

我需要这样第一个文本文件:

#1
Angel
Ghoul
Angry
black & waite
Cannon Pink

第二个文本文件:

#2
Angel
Ghoul
Angry
black & waite
Chelsea Cucumber

n文本文件:

#n
based on file name
based on file name
based on file name
based on file name
based on file name

文件名增量错误:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Angel    .Ghoul   .Angry    .black & waite     .Cannon Pink    ..png' -> '#01Angel    .Ghoul   .Angry    .black & waite     .Cannon Pink    ..png'

IIUC,尝试:

import os
import re
dir_path = "path/to/your/folder"
files = [f for f in os.listdir(dir_path) if f.endswith(".png")]
for i, file in enumerate(files):
with open(f"#{i+1} {file.replace('.png', '.txt')}", "w") as outfile:
outfile.write(f"#{i+1}n")
outfile.write("n".join(re.split("ss+", file[:-4].replace(".","").strip())))
os.rename(file, f"#{i+1} {file}")

最新更新