how to rename a file using python? - python

If the name is too long in the folder, there will be a problem, so I'm working on a code to change it at once. There's an error.
import os
import pathlib
p_dir = './data/'
for file in os.listdir(p_dir):
oldname = file
newname = file.split('_')[5] + '_SmmLogs.zip'
os.rename(oldname, newname)
I tried it like this, and from what I see, there seems to be no problem.
but..
Traceback (most recent call last): File "d:/Coding/name/namechange.py", line 15, in os.rename(oldname, newname) FileNotFoundError: [WinError 2] 指定されたファイルが見つかりません。: 'PN8B744_M0001_NewMDCR_4x4mmP_AllatOnce_20220328000119153_SmmLogs.zip' -> '20220328000119153_SmmLogs.zip
There's an error like this. Is there any way...?

listdir returns a list of filenames. You need to add the path p_dir to your filenames
for file in os.listdir(p_dir):
file_name = file
oldname = str(file_name)
newname1 = file.split('_')[5] + '_SmmLogs.zip'
newname = str(newname1)
os.rename(os.path.join(p_dir,oldname), os.path.join(p_dir,newname))

Related

Python, Tried making a script which takes all directorys and renames all the files in them

I tried making an python script which gets all directorys then
goes to the directorys and changes all the files name to the directory name.
The error :
Traceback (most recent call last):
File "D:\assets\steamcmd\yus.py", line 24, in <module>
os.rename(OurFilePath, os.path.join(pathy, pathname+str(file_extension)))
FileNotFoundError: [WinError 2] Nie można odnaleźć określonego pliku (cannot find file): 'steamapps\\workshop\\content\\573090\\2138774925\\.crash' -> 'steamapps\\workshop\\content\\573090\\2138774925\\2138774925
Code below which was used :
import os
directory = "steamapps\\workshop\\content\\573090\\"
for f in os.listdir(directory):
files = os.listdir()
pathy = os.path.join(directory, f)
for index,file in enumerate(files):
OurFilePath = os.path.join(pathy, file)
filename, file_extension = os.path.splitext(OurFilePath)
pathname = os.path.basename(pathy)
os.rename(OurFilePath, os.path.join(pathy, pathname+str(file_extension)))
Eventually, i found the error and have fixed the code.
The problem was : I used os.listdir the wrong way.
Heres the fixed code which i used :
directory = "steamapps\\workshop\\content\\573090\\"
for f in os.listdir(directory):
pathy = os.path.join(directory, f)
for file in os.listdir(pathy):
OurFilePath = os.path.join(pathy, file)
filename, file_extension = os.path.splitext(OurFilePath)
pathname = os.path.basename(pathy)
os.rename(os.path.join(os.path.join(directory, f), file), os.path.join(pathy, pathname+str(file_extension)))

Decompressing .bz2 files in a directory in python

I would like to decompress a bunch of .bz2 files contained in a folder (where there are also .zst files). What I am doing is the following:
destination_folder = "/destination_folder_path/"
compressed_files_path="/compressedfiles_folder_path/"
dirListing = os.listdir(compressed_files_path)
for file in dirListing:
if ".bz2" in file:
unpackedfile = bz2.BZ2File(file)
data = unpackedfile.read()
open(destination_folder, 'wb').write(data)
But I keep on getting the following error message:
Traceback (most recent call last):
File "mycode.py", line 34, in <module>
unpackedfile = bz2.BZ2File(file)
File ".../miniconda3/lib/python3.9/bz2.py", line 85, in __init__
self._fp = _builtin_open(filename, mode)
FileNotFoundError: [Errno 2] No such file or directory: 'filename.bz2'
Why do I receive this error?
You must be sure that all the file paths you are using exist.
It is better to use the full path to the file being opened.
import os
import bz2
# this path must exist
destination_folder = "/full_path_to/folder/"
compressed_files_path = "/full_path_to_other/folder/"
# get list with filenames (strings)
dirListing = os.listdir(compressed_files_path)
for file in dirListing:
# ^ this is only filename.ext
if ".bz2" in file:
# concatenation of directory path and filename.bz2
existing_file_path = os.path.join(compressed_files_path, file)
# read the file as you want
unpackedfile = bz2.BZ2File(existing_file_path)
data = unpackedfile.read()
new_file_path = os.path.join(destination_folder, file)
with bz2.open(new_file_path, 'wb') as f:
f.write(data)
You can also use the shutil module to copy or move files.
os.path.exists
os.path.join
shutil
bz2 examples

Python File Renaming Issue

import os
for filename in os.listdir("."):
if not filename.startswith("renamefilesindir"):
for filename2 in os.listdir(filename):
if filename2.startswith("abcdefghij"):
newName = "[abcdefghij.com][abcde fghij][" + filename + "][" + filename2[11:16] + "].jpg"
print(filename2)
print(newName)
os.rename(filename2, newName)
I have a folder with a few hundred other folders inside of it. Inside each secondary folder is a number of files all similarly named. What I want to do is rename each file, but I get the following error whenever I run the above program.
abcdefghij_88741-lg.jpg
[abcdefghij.com][abcde fghij][3750][88741].jpg
Traceback (most recent call last):
File "C:\directory\renamefilesindir.py", line 9, in <module>
os.rename(filename2, newName)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'abcdefghij_88741-lg.jpg' -> '[abcdefghij.com][abcde fghij][3750][88741].jpg'
I don't know what this means. It prints the existing file name, so I know it's found the file to be changed. Am I renaming the file wrong? What can't it find?
os.listdir contains just the names of the files and not the full paths. That's why your program actually tried to rename a file inside your current directory and it failed. So you could do the following:
import os.path
os.rename(os.path.join(filename, filename2), os.path.join(filename, newName))
since file with name filename2 is inside directory with name filename.

Python IOError: [Errno 2] from recursive directory call

The code below is part of a program I am writing that runs a method on every .py, .sh. or .pl file in a directory and its folders.
for root, subs, files in os.walk("."):
for a in files:
if a.endswith('.py') or a.endswith('.sh') or a.endswith('.pl'):
scriptFile = open(a, 'r')
writer(writeFile, scriptFile)
scriptFile.close()
else:
continue
When writing the program, it worked in the directory tree I wrote it in, but when I moved it to another folder to try it there I get this error message:
Traceback (most recent call last):
File "versionTEST.py", line 75, in <module>
scriptFile = open(a, 'r')
IOError: [Errno 2] No such file or directory: 'enabledLogSources.sh'
I know something weird is going on because the file is most definitely there...
You'll need to prepend the root directory to your filename
scriptFile = open(root + '/' + a, 'r')
files contains only the file names, not the entire path. The path to the file can be obtained by joining the file name and the root:
scriptFile = open(os.path.join(root, a), "r")
You might want to have a look at
https://docs.python.org/2/library/os.html#os.walk

Path error in python

I have written a script to rename a file
import os
path = "C:\\Users\\A\\Downloads\\Documents\\"
for x in os.listdir(path):
if x.startswith('i'):
os.rename(x,"Information brochure")
When the python file is in a different directory than the path I get a file not found error
Traceback (most recent call last):
File "C:\Users\A\Desktop\script.py", line 5, in <module>
os.rename(x,"Information brochure")
FileNotFoundError: [WinError 2] The system cannot find the file specified:'ib.pdf'-> 'Information brochure'
But if I copy the python file to the path location it works fine
import os
for x in os.listdir('.'):
if x.startswith('i'):
os.rename(x,"Information brochure")
What is the problem?
Your variable x is currently only the filename relative to path. It's what os.listdir(path) outputs. As a result, you need to prepend path to x using os.path.join(path,x).
import os
path = "C:\\Users\\A\\Downloads\\Documents\\" #os.path.join for cross-platform-ness
for x in os.listdir(path):
if x.startswith('i'): # x, here is the filename. That's why it starts with i.
os.rename(os.path.join(path,x),os.path.join(path,"Information brochure"))
The x variable has the name of the file but not the full path to the file. Use this:
os.rename(path + "\\" + x, "Information brochure")

Categories