Python Unzipping files with different name to a different location - python

I am trying to extract the files from a zip archive and appending "EI" to each file inside it. I want these files to be extracted in a certain location. I'm new to python, hence unable to figure out.
for i in zip_list:
if ("Rally-EI" in i):
zipdata = zipfile.ZipFile(i)
zipinfos = zipdata.infolist()
for zipinfo in zipinfos:
zipinfo.filename = zipinfo.filename[:-4] + "_EI.txt"
zipdata.extract(zipinfo)
This is the code I'm using for appending the file name and it is working well. Need to extract these files to a specific location.
Thanks

Try using os.chdir() to change the current directory temporarily for this extraction. It's not the most efficient way, but, it will do the work.
Do save your current working directory using os.getcwd() to revert back to the original working directory after the extraction is done.

Related

Python, Inconsistent zip file extraction

I am trying to extract zip files using the zipfile module's extractall method.
My code snippet is
import zipfile
file_path = '/something/airway.zip'
dir_path = 'something/'
with zipfile.ZipFile(file_path, "r") as zip_ref:
zip_ref.extractall(dir_path)
I have two zip files named, test (1.1 mb) and airway (520 mb).
For test.zip the folder contains all the files but for airway.zip, it creates another folder inside my target folder named Airway, and then extracts all the files there. Even after renaming the airway.zip to any garbage name, the result was same.
Is there some workaround to get only the files extracted in my target folder? It is critical for me as I'm doing this extraction automated from django
Python version: 3.9.6;
Django version: 2.2
I ran your code and it seems to be only a problem of the zipfile itself. If you create a zipfile by selecting only the elements you get the result you got with test.zip. If you create it by selecting a folder holding the elements the folder will be there if you extract it again, no matter what you name your zip file.
I have two articles related to this:
https://www.kite.com/python/docs/zipfile.ZipFile.extractall
https://www.geeksforgeeks.org/working-zip-files-python/
Even if both of these articles do not solve your problem then I think that instead of zipping the files in the folder you just zipped the folder itself so try by zipping the files inside the folder.

Python: How to read multiple .NBT files and export to JSON?

I am a newbie when it comes to programming and i'm looking for a way to iterate through a directory filled with .NBT files and export them to JSON.
I know i can loop thorugh a directory using os.listdir, but i have trouble reading the files one by one and deciding what steps to take in order to get it to a JSON format.
The actual assignment is to loop through a bunch of .NBT files to see which Minecraft crate is faced towards with direction.
This is what i have now:
import python_nbt.nbt as nbt
import os
for file in os.listdir("Directory to nbt files"):
if file.endswith(".nbt"):
filename = nbt.read_from_nbt_file(file)
From here i get a FileNotFoundError saying there is no such file or directory.
What am i doing wrong?
And what must be done to continue?
you didn't specified the folder the file is in:
do nbt.read_from_nbt_file('Directory to nbt files' + '\\' + file)

How to rename a file in certain directory? [duplicate]

This question already has answers here:
Using os.walk() to recursively traverse directories in Python
(14 answers)
Closed 2 years ago.
I hope everyone is staying safe and sound.
Could you please help me with file name change in certain directory?
I am writing a script for RDA to download documents from this website, and when I download these files from this website, file names do not have pattern, it is completely random. So I want to rename these files into certain pattern.
For example,
1st downloaded file name: filedownload.pdf
rename to: 1234567.pdf
2nd downloaded file name: extractpages.pdf
rename to: 1234568.pdf
new names are set in parameter so that part is good but as I don't know what downloaded file name will be, I can't change this file name into new name.
So what I had in mind is for each downloaded file, put it in this folder without any files, and whenever any file is located in this folder, it renames the file and put it in different folder.
Below is the code I wrote;
filepath = "originalFilePath/downloadedfile.pdf"
if os.path.isfile(filepath):
os.rename(r'originalFilePath/downloadedfile.pdf',
'newFilePath' + str(parameter['search_number']) + '.pdf')
But I would like to change file names no matter what the downloaded file name is.
Please help, thank you very much!!
I think your idea is quite correct.
First, you will list all file name in a folder before downloading anything, store that list in a variable, let's say current_files. Then you start downloading files from the web, after that, you list all the file name again and store in the second list. Now you will compare 2 lists and know what files are new (just downloaded). Then you just simply loop over these new files and rename it in a pattern that you want. I will add code in a minute
import glob
current_files = glob.glob("/path/Downloads/*.pdf")
# ['path/Downloads/abc.pdf', 'path/Downloads/xyz.pdf']
# your code to download files from the web
new_files = set(glob.glob("/path/Downloads/*.pdf")) - set(current_files)
# ['path/Downloads/just_downloaded1.pdf', 'path/Downloads/just_downloaded2.pdf']
for file in new_files:
#do the rename code here to your new files
You question is not totally clear.
Anyway I think you have an issue with your code, you have to add / after newFilePath.
Use os.renames(old, new).
os.renames(old, new)
Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs().
References
https://docs.python.org/3/library/os.html

Lost files while tried to move files using python shutil.move

I had 120 files in my source folder which I need to move to a new directory (destination). The destination is made in the function I wrote, based on the string in the filename. For example, here is the function I used.
path ='/path/to/source'
dropbox='/path/to/dropbox'
files = = [os.path.join(path,i).split('/')[-1] for i in os.listdir(path) if i.startswith("SSE")]
sam_lis =list()
for sam in files:
sam_list =sam.split('_')[5]
sam_lis.append(sam_list)
sam_lis =pd.unique(sam_lis).tolist()
# Using the above list
ID = sam_lis
def filemover(ID,files,dropbox):
"""
Function to move files from the common place to the destination folder
"""
for samples in ID:
for fs in files:
if samples in fs:
desination = dropbox + "/"+ samples + "/raw/"
if not os.path.isdir(desination):
os.makedirs(desination)
for rawfiles in fnmatch.filter(files, pat="*"):
if samples in rawfiles:
shutil.move(os.path.join(path,rawfiles),
os.path.join(desination,rawfiles))
In the function, I am creating the destination folders, based on the ID's derived from the files list. When I tried to run this for the first time it threw me FILE NOT exists error.
However, later when I checked the source all files starting with SSE were missing. In the beginning, the files were there. I want some insights here;
Whether or not os.shutil.move moves the files to somewhere like a temp folder instead of destination folder?
whether or not the os.shutil.move deletes the files from the source in any circumstance?
Is there any way I can test my script to find the potential reasons for missing files?
Any help or suggestions are much appreciated?
It is late but people don't understand the op's question. If you move a file into a non-existing folder, the file seems to become a compressed binary and get lost forever. It has happened to me twice, once in git bash and the other time using shutil.move in Python. I remember the python happens when your shutil.move destination points to a folder instead of to a copy of the full file path.
For example, if you run the code below, a similar situation to what the op described will happen:
src_folder = r'C:/Users/name'
dst_folder = r'C:/Users/name/data_images'
file_names = glob.glob(r'C:/Users/name/*.jpg')
for file in file_names:
file_name = os.path.basename(file)
shutil.move(os.path.join(src_folder, file_name), dst_folder)
Note that dst_folder in the else block is just a folder. It should be dst_folder + file_name. This will cause what the Op described in his question. I find something similar on the link here with a more detailed explanation of what went wrong: File moving mistake with Python
shutil.move does not delete your files, if for any reason your files failed to move to a given location, check the directory where your code is stored, for a '+' folder your files are most likely stored there.

Errno13, Permission denied when trying to read file

I have created a small python script. With that I am trying to read a txt file but my access is denied resolving to an no.13 error, here is my code:
import time
import os
destPath = 'C:\Users\PC\Desktop\New folder(13)'
for root, dirs, files in os.walk(destPath):
f=open(destPath, 'r')
.....
Based on the name, I'm guessing that destPath is a directory, not a file. You can do a os.walk or a os.listdir on the directory, but you can't open it for reading. You can only call open on a file.
Maybe you meant to call open on one or more of the items from files
1:
I take it you are trying to access a file to get what's inside but don't want to use a direct path and instead want a variable to denote the path. This is why you did the destPath I'm assuming.
From what I've experienced the issue is that you are skipping a simple step. What you have to do is INPUT the location then use os.CHDIR to go to that location. and finally you can use your 'open()'.
From there you can either use open('[direct path]','r') or destPath2 = 'something' then open(destPath2, 'r').
To summarize: You want to get the path then NAVIGATE to the path, then get the 'filename' (can be done sooner or not at all if using a direct path for this), then open the file.
2: You can also try adding an "r" in front of your path. r'[path]' for the raw line in case python is using the "\" for something else.
3: Try deleting the "c:/" and switching the / to \ or vice versa.
That's all I got, hope one of them helps! :-)
I got this issue when trying to create a file in the path -C:/Users/anshu/Documents/Python_files/Test_files . I discovered python couldn't really access the directory that was under the user's name.
So, I tried creating the file under the directory - C:/Users/anshu/Desktop .
I was able to create files in this directory through python without any issue.

Categories