Mainland
Mainland

Reputation: 4604

How to batch convert "File" type files to "text" type files

I have many "File" type files. I want to convert them into "Text" files.

Screenshot of files is given below:

I want to convert these files into "Text" files. My code is given below:

    os.chdir('FolderName/')
    extension = 'txt'
    raw_filenames = [i for i in glob.glob('*')]   ### len(all_filenames1)
    text_filenames = ['%s'%(i).format(extension) for i in raw_filenames]
    print(len(text_filenames))
    print(type(raw_filenames[0]))
    print(type(text_filenames[0]))

Output:

    108
    <class 'str'>
    <class 'str'>

Above code is running successfully but not converting the files to .txt format. I am trying to do two things:

  1. How to convert these file into txt format and
  2. save them with same name back to same folder?

Upvotes: 1

Views: 2304

Answers (2)

BPL
BPL

Reputation: 9863

Here's a little example to rename recursively files using pathlib and os.rename combo:

from pathlib import Path
import os
import sys

basedir = Path("FolderName").resolve(strict=True)
print(f"Renaming files in {basedir}")

prefix = "\\\\?\\" if sys.platform == "win32" else ""

for src in basedir.glob("**/*"):
    if src.is_dir():
        continue

    dst = src.with_suffix('.txt')
    if not dst.exists():
        try:
            os.rename(f"{prefix}{src}", f"{prefix}{dst}")
            print(f"Renamed {src}")
        except Exception as e:
            print(f"Error renaming: {e}")

On Windows, if dst exists a FileExistsError is always raised, that's why you should check if dst already exists. Also, it may happen that because some paths being too long os.rename could raise a [WinError 3] exception, that's why using the prefix "\?\".

For more info about [WinError 3] you can check the docs here https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation

Upvotes: 1

ivallesp
ivallesp

Reputation: 2222

I think renaming would work. Check the following code

import os
import glob

os.chdir('FolderName/')
extension = 'txt'
raw_filenames = [i for i in glob.glob('*')]   ### len(all_filenames1)
text_filenames = ['%s'%(i).format(extension) for i in raw_filenames]
print(len(text_filenames))
print(type(raw_filenames[0]))
print(type(text_filenames[0]))

for in, out in zip(raw_filename, text_filenames)
    os.rename(in, out)

Upvotes: 1

Related Questions