Home > database >  python with open - rename file
python with open - rename file

Time:10-29

I am using python with open to read a file.

with open('/Users/ks/Downloads/file name 1.pdf', 'rb') as data:
    print(data)

<_io.BufferedReader name='/Users/ks/Downloads/file name 1.pdf'>

I am trying to rename the file to file_name_1.pdf before uploading. Is there a way to parse the file name from data and rename? I'd like to replace with _.

CodePudding user response:

Rename the file with this:

import os
file_path = '/Users/kevalshah/Downloads/file name 1.pdf'
os.rename(file_path, file_path.replace(' ', '_'))

to rename from data you need this:

import os
file_path = '/Users/kevalshah/Downloads/file name 1.pdf'
with open(file_path, 'rb') as data:
    file_path = data.name

# !!! file was closed first
os.rename(file_path, file_path.replace(' ', '_'))

CodePudding user response:

pathlib can help make sure you don't mess anything up unexpectedly. There's no reason to open a file just to change its name:

from pathlib import Path

file_path = '/Users/kevalshah/Downloads/file name 1.pdf'

# Convert to Path
file_path = Path(file_path)

# Modify the Name 
# Use .name attribute to ensure you're just modifying the filename
new_name = file_path.name.replace(' ', '_')

# Use .with_name and .rename to modify the filename:
file_path = file_path.rename(file_path.with_name(new_name)))
# Your file has been renamed~
  • Related