I want to assign to my zipfile from a variable named file_path, how I can do that? I tried with the code below, and this line is the problem:
with ZipFile('%s.zip' %(file_path,),'w') as zip:
Nothing happens; I get no errors just Python doesn't create the .zip file. Here is all the code.
import os
from zipfile import ZipFile
file_paths = []
basepath = 'my_directory/'
with os.scandir(basepath) as entries:
for root, directories, files in os.walk(basepath):
for entry in entries:
if entry.is_file():
file_path = os.path.join(entry)
file_paths.append(file_path)
with ZipFile('%s.zip' %(file_path,),'w') as zip:
print("FILE:", entry.name)
for entry in file_paths:
zip.write(entry)
I stumbled upon this unanswered query while I was go though something else, a simple work around would be to use .format as below
with ZipFile('{}.zip'.format(d),'w') as zip:
Related
I have a zip file in a directory. I want to read out the contents of the zipfile and after this move its content to other directories to auto sort my zipped files. thing is, the name of these zipfiles will change everytime.
I learned about glob being able to handle the asterix for this normally, but it doesn't work with the zipfile import.
I tried:
from zipfile import ZipFile
from glob import glob
path_to_zip = glob(r"C:\me\Python\map_dumper\*.zip")
with ZipFile(path_to_zip, "r") as read_zip:
ZipFile.namelist()
This gives me an AttributeError:'list' object has no attribute 'seek'
anyone know of another solution for this?
glob.glob gives you list of filenames compliant with what you specify, for example
glob(r"C:\me\Python\map_dumper\*.zip")
is list of all zip files inside map_dumper catalog, you might use for loop to apply your action to every such file following way
from zipfile import ZipFile
from glob import glob
files_list = glob(r"C:\me\Python\map_dumper\*.zip")
for path_to_zip in files_list:
with ZipFile(path_to_zip, "r") as read_zip:
ZipFile.namelist()
In multiple folders I have a file called _status.json
e.g.:
C:\Users\Me\.fscrawler\Folder1\_status.json
C:\Users\Me\.fscrawler\Folder2\_status.json
....
C:\Users\Me\.fscrawler\*\_status.json
I want to write a short python code, to delete all those files.
I already tried the following code, but it does not work. I dont know why, but I think the solution is pretty easy
import os
os.remove(C:\Users\Me\.fscrawler\*\_status.json)
You will have to walk through all the subfolders to find and delete the file.
for root, dirs, files in os.walk(folder_path):
for name in files:
if name == '_status.json':
#delete the file
I would look into the glob module, and use it to find the files:
example:
import glob
relative_path_to_files = glob.glob('**/_status.json', recursive=True)
then you can operate on the list as you wish :)
Edit:
relative_path_to_files is a list, so you have to iterate over its elements and operate on them:
here is a complete example to find all _status.json in the current directory and its sub-tree recursively:
import glob
import os
for f in glob.glob('**/_status.json', recursive=True):
os.remove(f)
I'm trying to simply move files from folder path1 to folder path.
import os
import shutil
path1 = '/home/user/Downloads'
file_dir = os.listdir(path1)
fpath = '/home/user/music'
for file in file_dir:
if file.endswith('.mp3'):
shutil.move(os.path.join(file_dir,file), os.path.join(fpath, file))
... but I get this error
TypeError: expected str, bytes or os.PathLike object, not list
First of all, you shouldn't use file as a variable name, it's a builtin in python, consider using f instead.
Also notice that in the shutil.move line, I've changed your (os.path.join(file_dir,f) to (os.path.join(path1,f). file_dir is a list, not the name of the directory that you're looking for, that value is stored in your path1 variable.
Altogether, it looks like this:
import os
import shutil
path1 = '/home/user/Downloads'
file_dir = os.listdir(path1)
fpath = '/home/user/music'
for f in file_dir:
if f.endswith('.mp3'):
shutil.move(os.path.join(path1,f), os.path.join(fpath, f))
You have confused your variable purposes from one line to the next. You've also over-built your file path construction.
You set up file_dir as a list of all the files in path1. That works fine through your for command, where you iterate through that list. The move method requires two file names, simple strings. Look at how you construct your file name:
os.path.join(file_dir,file)
Remember, file_dir is a list of files in path1. file is one of the files in that list. What are you trying to do here? Do you perhaps mean to concatenate path1 with file?
NOTE: Using pre-defined names as variables is really bad practice. file is a pre-defined type. Instead, use f or local_file, perhaps.
Read carefully the error message. file_dir is list. You can not join it with os.path.join. You probably want to write:
shutil.move(os.path.join(path1, f), os.path.join(fpath, f))
I suggest to name variables with meaningful names like:
file_list = os.listdir(path1)
This way you will not join a file list with a path :)
There is an mkv file in a folder named "export". What I want to do is to make a python script which fetches the file name from that export folder.
Let's say the folder is at "C:\Users\UserName\Desktop\New_folder\export".
How do I fetch the name?
I tried using this os.path.basename and os.path.splitext .. well.. didn't work out like I expected.
os.path implements some useful functions on pathnames. But it doesn't have access to the contents of the path. For that purpose, you can use os.listdir.
The following command will give you a list of the contents of the given path:
os.listdir("C:\Users\UserName\Desktop\New_folder\export")
Now, if you just want .mkv files you can use fnmatch(This module provides support for Unix shell-style wildcards) module to get your expected file names:
import fnmatch
import os
print([f for f in os.listdir("C:\Users\UserName\Desktop\New_folder\export") if fnmatch.fnmatch(f, '*.mkv')])
Also as #Padraic Cunningham mentioned as a more pythonic way for dealing with file names you can use glob module :
map(path.basename,glob.iglob(pth+"*.mkv"))
You can use glob:
from glob import glob
pth ="C:/Users/UserName/Desktop/New_folder/export/"
print(glob(pth+"*.mkv"))
path+"*.mkv" will match all the files ending with .mkv.
To just get the basenames you can use map or a list comp with iglob:
from glob import iglob
print(list(map(path.basename,iglob(pth+"*.mkv"))))
print([path.basename(f) for f in iglob(pth+"*.mkv")])
iglob returns an iterator so you don't build a list for no reason.
I assume you're basically asking how to list files in a given directory. What you want is:
import os
print os.listdir("""C:\Users\UserName\Desktop\New_folder\export""")
If there's multiple files and you want the one(s) that have a .mkv end you could do:
import os
files = os.listdir("""C:\Users\UserName\Desktop\New_folder\export""")
mkv_files = [_ for _ in files if _[-4:] == ".mkv"]
print mkv_files
If you are searching for recursive folder search, this method will help you to get filename using os.walk, also you can get those file's path and directory using this below code.
import os, fnmatch
for path, dirs, files in os.walk(os.path.abspath(r"C:/Users/UserName/Desktop/New_folder/export/")):
for filename in fnmatch.filter(files, "*.mkv"):
print(filename)
You can use glob
import glob
for file in glob.glob('C:\Users\UserName\Desktop\New_folder\export\*.mkv'):
print(str(file).split('\')[-1])
This will list out all the files having extention .mkv as
file.mkv, file2.mkv and so on.
From os.walk you can read file paths as a list
files = [ file_path for _, _, file_path in os.walk(DIRECTORY_PATH)]
for file_name in files[0]: #note that it has list of lists
print(file_name)
I know how to use python to check to see if a file exists, but what I am after is trying to see if multiple files of the same name exist throughout my working directory. Take for instance:
gamedata/areas/
# i have 2 folders in this directory
# testarea and homeplace
1. gamedata/areas/testarea/
2. gamedata/areas/homeplace/
Each folder of homeplace and testarea for instance contains a file called 'example'
Is there a pythonic way to use 'os' or similiar to check to see if the file 'example' can be found in both testarea and homeplace?
Although is their a way to do this without manually and statically using
os.path.isfile()
because throughout the life of the program new directories will be made, and I don't want to constantly go back into the code to change it.
You can check in every directory bellow gamedata/areas/:
This only goes down one level, you could extend it to go down as many levels as you want.
from os import listdir
from os.path import isdir, isfile, join
base_path = "gamedata/areas/"
files = listdir(base_path)
only_directories = [path for path in files if isdir(join(base_path,path))]
for directory_path in only_directories:
dir_path = join(base_path, directory_path)
for file_path in listdir(dir_path):
full_file_path = join(base_path, dir_path, file_path)
is_file = isfile(full_file_path)
is_example = "example" in file_path
if is_file and is_example:
print "Found One!!"
Hope it helps!
Maybe something like
places = ["testarea", "homeplace"]
if all(os.path.isfile(os.path.join("gamedata/areas/", x, "example") for x in places)):
print("Missing example")
If the condition is false, this doesn't tell you which subdirectory does not contain the file example, though. You can update places as necessary.
As I mentioned in the comments, os.walk is your friend:
import os
ROOT="gamedata/areas"
in_dirs = [path for (path, dirs, filenames)
in os.walk(ROOT)
if 'example' in filenames]
in_dirs will be a list of subdirectories where example is found