Python reading unopened files from a folder - python

Is there a way to read all the unopened files in a folder only by passing the one specific file name that is present in that folder?I know to read all the files in a directory passing the directory name using os.walk.But in this specific problem I can just pass only one file name.Need your help for this problem.Thank you.

If I understand you correctly, you have a path of a single file, while you want to read all files in the folder it's located in.
You can achieve this easily:
dir_name, file_name = os.path.split(filepath)
for root, dirs, files in os.walk(dir_name):
for file in files:
with open(file) as f:
file_content = f.read()

Related

Unzipping a file with subfolders into the same directory without creating an extra folder

I hope I don't duplicate here, but I didn't find a solution until now since the answers don't include subfolders. I have a zipfile that contains a folder which contains files and subfolders.
I want to extract the files within the folder (my_folder) and the subfolder to a specific path: Users/myuser/Desktop/another . I want only files and subfolders in the another dir. With my current code what happens it that a directory my_folder is created in which my files and subfolders are placed. But I don't want that directory created. This is what I am doing:
with zipfile.ZipFile("Users/myuser/Desktop/another/my_file.zip", "r") as zip_ref:
zip_ref.extractall(Users/myuser/Desktop/another)
I tried listing all the zipfiles within the folder and extracting them manually:
with ZipFile('Users/myuser/Desktop/another/myfile.zip', 'r') as zipObj:
# Get a list of all archived file names from the zip
listOfFileNames = zipObj.namelist()
for fileName in new_list_of_fn:
print(fileName)
zipObj.extract(fileName, 'Users/myuser/Desktop/another/')
This yields the same result. I the tried create a new list, stripping the names so that they don't include the name of the folder anymore but then it tells me that there is no item named xyz in the archive.
Finally I leveraged those two questions/code (extract zip file without folder python and Extract files from zip without keeping the structure using python ZipFile?) and this works, but only if there are no subfolders involved. If there are subfolders it throws me the error FileNotFoundError: [Errno 2] No such file or directory: ''. What I want though is that the files in the subdirectory get extracted to the subdirectory.
I can only use this code if I skip all directories:
my_zip = Users/myuser/Desktop/another/myfile.zip
my_dir = Users/myuser/Desktop/another/
with zipfile.ZipFile(my_zip, 'r') as zip_file:
for member in zip_file.namelist():
filename = os.path.basename(member)
print(filename)
# skip directories
if not filename:
continue
# copy file (taken from zipfile's extract)
source = zip_file.open(member)
target = open(os.path.join(my_dir, filename), "wb")
with source, target:
shutil.copyfileobj(source, target)
So I am looking for a way to do this which would also extract subdirs to their respective dir. That means I want a structure within /Users/myuser/Desktop/another:
-file1
-file2
-file3
...
- subfolder
-file1
-file2
-file3
...
I have the feeling this must be doable with shututil but don't really know how....
Is there a way I can do this? Thanks so much for any help. Very much appreciated.

How to extract zip file in different directory in python?

I'm writing a python (2.7) script that extracts files from a zip file with an encrypted password. For this, I'm using the ZipFile module to extract files in a different directory. I have followed all the answer whatever is mentioned on here. How to extract all the files from the zip file into a different directory?
I have tried to extract all files into different directories but result is: it is creating directory inside the targeted directory.
try:
with ZipFile(os.path.join(app.config['UPLOAD_FOLDER'], filename)) as zf:
zf.extractall('/Users/dipak.das/desktop/docs/',None,b'12345')
except RuntimeError as e:
print e
I expected the output of the above script should extract all files inside path directories.But my code is creating a directory inside docs directories "/Users/dipak.das/desktop/docs/" and extracting all files.
Assuming that you want the files extracted with no subdirectories...
Totally untested but perhaps try something like
import os, shutil
destdir = '/Users/dipak.das/desktop/docs/'
with ZipFile(os.path.join(app.config['UPLOAD_FOLDER'], filename)) as zf:
for name in zf.namelist():
source = zf.open(name, 'r', b'12345')
destpath = os.path.join(destdir, os.path.basename(name))
target = open(destpath, 'w')
shutil.copyfileobj(source, target)
target.close()

Copy text file content and paste it to another

I've searched for a while for the solution, so I won't bother you, but I can't find it for my problem.
I want to copy text from .txt file and paste it to another one. The problem is, I've got a bunch of these files.
I've tried to do this in python, as I have the previous script to add a new line to .txt file based on the folder name, but I just can't figure it myself.
So what I did so far based on research is:
import os
rootdir = 'FOLDERS'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file == 'opis.txt':
source = '%s.txt' % subdir
if os.path.exists(source):
target = os.path.join(subdir, file)
with open(source) as source_file:
with open(target, 'a') as target_file:
target_file.write(source_file.read())
In folder 'FOLDERS' I have .txt files that have a name as a folder containing "opis.txt" file (where I want to paste text from the text file with folder name), e.g.
\FOLDERS\P.1417.1969.11.txt
\FOLDERS\P.1417.1969.11\opis.txt
I want to copy the line starting with "R:" (or just whole file content, as this line is the only text there) from the P.1417.1969.11.txt file and paste it to P.1417.1969.11\opis.txt
I have hundreds of files and folders with corresponding names, that's why I need a script.
EDIT: I've changed the code to the one that works.

python is showing a excel file that is not present in a folder

Basically i'm trying to print all excel files in a directory. In one of the folders, i don't have a excel file named '~$EndManifold-4Slot.xlsm', but while printing the files, i see this is present, which is actually not there.
Could anyone suggest on how to improve the same?
def Fnfolders(rootdir):
xlFilesList=[]
for dirname, dirnames, filenames in os.walk(rootdir):
for file in os.listdir(dirname):
if '.xls' in file or '.xlsx' in file:
fullPath=os.path.join(dirname)+"\\"+file
xlFilesList.append(fullPath)
return xlFilesList
xlFilesList=Fnfolders(rootdir)
for excel in xlFilesList:
print (excel)
Normally, files like - ~$EndManifold-4Slot.xlsm are temporary files created when you openned your file in Excel. they are usually hidden, you can find them in your explorer if you enable Show Hidden Files in folder options.
You can read more about those temporary files here .

Zipping only files in Python

So I create several files in some temp directory dictated by NamedTemporaryFile function.
zf = zipfile.ZipFile( zipPath, mode='w' )
for file in files:
with NamedTemporaryFile(mode='w+b', bufsize=-1, prefix='tmp') as tempFile:
tempPath = tempFile.name
with open(tempPath, 'w') as f:
write stuff to tempPath with contents of the variable 'file'
zf.write(tempPath)
zf.close()
When I use the path of these files to add to a zip file, the temp directories themselves get zipped up.
When I try to unzip, I get a series of temp folders, which eventually contain the files I want.
(i.e. I get the folder Users, which contains my user_id folder, which contains AppData...).
Is there a way to add the files directly, without the folders, so that when I unzip, I get the files directly? Thank you so much!
Try giving the arcname:
from os import path
zf = zipfile.ZipFile( zipPath, mode='w' )
for file in files:
with NamedTemporaryFile(mode='w+b', bufsize=-1, prefix='tmp') as tempFile:
tempPath = tempFile.name
with open(tempPath, 'w') as f:
write stuff to tempPath with contents of the variable 'file'
zf.write(tempPath,arcname=path.basename(tempPath))
zf.close()
Using os.path.basename you can get the file's name from a path. According to zipfile documentation, the default value for arcname is filename without a drive letter and with leading path separators removed.
Try using the arcname parameter to zf.write:
zf.write(tempPath, arcname='Users/mrb0/Documents/things.txt')
Without knowing more about your program, you may find it easier to get your arcname from the file variable in your outermost loop rather than deriving a new name from tempPath.

Categories

Resources