Home > Blockchain >  creating text file for each file in directory with python
creating text file for each file in directory with python

Time:11-24

i created this with autohotkey but i couldn't organize them

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

so i decided to write it with python but i can't make text file for each filename with os lib and i can't remove dots or custom layout from filenames in text file

here my code :

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")  

      

file names are like this :

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

and output of this script without renaming incremental number:

Angel

.Ghoul
 .Angry

.black & waite

 .Cannon Pink

i need to be like this first text file:

#1
Angel
Ghoul
Angry
black & waite
Cannon Pink

second text file:

#2
Angel
Ghoul
Angry
black & waite
Chelsea Cucumber

n text file:

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

errors from incremental number for filenames:

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'

CodePudding user response:

IIUC, try:

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("\s\s ", file[:-4].replace(".","").strip())))
    os.rename(file, f"#{i 1} {file}")
  • Related