Python zipfile is directory

How do I determine whether an item in python ZipFile is dir or file?

If, on the other hand, you want to leave the file alone if it exists, but put specific non-empty contents there otherwise, then more complicated approaches based on / statement blocks are probably more suitable. Solution 1: As you yourself said, just open the file and check if it is in it.

How to check if a file is a directory or regular file in python? [duplicate]

How do you check if a path is a directory or file in python?

os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory? os.path.isdir("bob") 

more info here http://docs.python.org/library/os.path.html

Many of the Python directory functions are in the os.path module.

An educational example from the stat documentation:

import os, sys from stat import * def walktree(top, callback): '''recursively descend the directory tree rooted at top, calling the callback function for each regular file''' for f in os.listdir(top): pathname = os.path.join(top, f) mode = os.stat(pathname)[ST_MODE] if S_ISDIR(mode): # It's a directory, recurse into it walktree(pathname, callback) elif S_ISREG(mode): # It's a file, call the callback function callback(pathname) else: # Unknown file type, print a message print 'Skipping %s' % pathname def visitfile(file): print 'visiting', file if __name__ == '__main__': walktree(sys.argv[1], visitfile) 

How to check if an data already present in a CSV file, Good day all, I am trying to write a python script that picks up IP address(es) from a textfile, check if the IP addresses already present in CSV file, …

Читайте также:  Send html message telegram bot

How do I determine whether an item in python ZipFile is dir or file?

This is my current system, which just looks to see whether there is a period in the path. but that doesn’t work in all cases

 with ZipFile(zipdata, 'r') as zipf: #Open the .zip BytesIO in Memory mod_items = zipf.namelist() #Get the name of literally everything in the zip for folder in mod_folders: mod_items.insert(0, folder) #Put the folder at the start of the list #This makes sure that the folder gets created #Search through every file in the .zip for each folder indicated in the save for item in mod_items: if folder in item: #If the item's path indicates that it is a member of the folder itempath = item #Make a copy of the if not itempath.startswith(folder): itempath = path_clear(itempath, folder) if not 'GameData/' in itempath: itempath = 'GameData/' + itempath path = mod_destination_folder + '/' + itempath path = path_clear(path) dot_count = path.count('.') if dot_count: #Is a normal file, theoretically itemdata = zipf.read(item) try: with open(path, 'wb') as file: file.write(itemdata) except FileNotFoundError as f: folder_path = path[:path.rfind('/')] makedirs(folder_path) with open(path, 'wb') as file: file.write(itemdata) else: #Is a folder try: makedirs(path) except: pass 

All I need is some sort of way to determine whether: A) Whether the folder is one of the folders desired by the user B) For each item in that folder is a directory or a file

You can also use infolist instead of namelist to get ZipInfo objects directly instead of names.

Alternatively, check the name — directories will end with / . (This is the same check that is_dir performs.)

Python — Check if a file or directory exists, os.path.isdir () method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic …

Check if a string is in a file with Python [duplicate]

I’m new to Python and I’m trying to figure out how I can Search for a string in a file and use it as a condition in a if clause: If «String» is in the file, Print(«Blablabla»)

As you yourself said, just open the file and check if it is in it.

with open('myfile.txt') as myfile: if 'String' in myfile.read(): print('Blahblah') 

This is the top answer from a very similar question.

if 'blabla' in open('example.txt').read(): print "true" 

In Python, how do I determine if an object is iterable?, In Python

Pythonic way to check if a file exists? [duplicate]

Which is the preferred way to check if a file exists and if not create it?

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

Instead of os.path.isfile , suggested by others, I suggest using os.path.exists , which checks for anything with that name, not just whether it is a regular file.

if not os.path.exists(filename): file(filename, 'w').close() 

The latter will create the file if it exists, but not otherwise. It will, however, fail if the file exists, but you don’t have permission to write to it. That’s why I prefer the first solution.

It seems to me that all other answers here (so far) fail to address the race-condition that occurs with their proposed solutions.

Any code where you first check for the files existence, and then, a few lines later in your program, you create it, runs the risk of the file being created while you weren’t looking and causing you problems (or you causing the owner of «that other file» problems).

If you want to avoid this sort of thing, I would suggest something like the following (untested):

import os def open_if_not_exists(filename): try: fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY) except OSError, e: if e.errno == 17: print e return None else: raise else: return os.fdopen(fd, 'w') 

This should open your file for writing if it doesn’t exist already, and return a file-object. If it does exists, it will print «Ooops» and return None (untested, and based solely on reading the python documentation, so might not be 100% correct).

If (when the file doesn’t exist) you want to create it as empty, the simplest approach is

(in Python 2.6 or better; in 2.5, this requires an «import from the future» at the top of your module).

If, on the other hand, you want to leave the file alone if it exists, but put specific non-empty contents there otherwise, then more complicated approaches based on if os.path.isfile(thepath): / else statement blocks are probably more suitable.

How to check in Python if string is in a text file and print, w = raw_input («Input the English word: «) # For Python 3: use input () instead with open (‘foo.txt’) as f: found = False for line in f: if w in line: # Key line: check if `w` …

Источник

Check if a directory exists in a zip file with Python

Initially I was thinking of using os.path.isdir but I don’t think this works for zip files. Is there a way to peek into the zip file and verify that this directory exists? I would like to prevent using unzip -l «$@» as much as possible, but if that’s the only solution then I guess I have no choice.

4 Answers 4

Just check the filename with «/» at the end of it.

import zipfile def isdir(z, name): return any(x.startswith("%s/" % name.rstrip("/")) for x in z.namelist()) f = zipfile.ZipFile("sample.zip", "r") print isdir(f, "a") print isdir(f, "a/b") print isdir(f, "a/X") 
any(x.startswith("%s/" % name.rstrip("/")) for x in z.namelist()) 

because it is possible that archive contains no directory explicitly; just a path with a directory name.

$ mkdir -p a/b/c/d $ touch a/X $ zip -r sample.zip a adding: a/ (stored 0%) adding: a/X (stored 0%) adding: a/b/ (stored 0%) adding: a/b/c/ (stored 0%) adding: a/b/c/d/ (stored 0%) $ python z.py True True False 

Thanks! Well this worked with the sample you provided. But I’m trying to do this for docx files. Essentially I’m checking if the zip file contains the directory «word», but it’s giving me false responses 🙁

Just try to print the list of files in your docx and see what is strange with it: print zipfile.ZipFile(«sample.docx», «r»).namelist()

word/_rels/document.xml.rels This is a file contained it in, I printed it straight out of z.namelist()

You can check for the directories with ZipFile.namelist().

import os, zipfile dir = "some/directory/" z = zipfile.ZipFile("myfile.zip") if dir in z.namelist(): print "Found %s!" % dir 

Yea, I made sure the directory is there. I’m trying to do it for docx files, which are zip files anyways so that shouldn’t matter right?

Oh I found the issue, the list doesn’t contain the directory «word» by itself, rather it contains all the files.

for python(>=3.6):

this is how the is_dir() implemented in python source code:

def is_dir(self): """Return True if this archive member is a directory.""" return self.filename[-1] == '/' 

It simply checks if the filename ends with a slash / , Can’t tell if this will work correctly in some certain circumstances(so IMO it is badly implemented).

for python(<3.6):

as print(zipinfo) will show filemode but no corrsponding property or field is provided, I dive into zipfile module source code and found how it is implemented. (see def __repr__(self): https://github.com/python/cpython/blob/3.6/Lib/zipfile.py)

possibly a bad idea but it will work:

if you want something simple and easy, this will work in most cases but it may fail because in some cases this field will not be printed.

def is_dir(zipinfo): return "filemode='d" in zipinfo.__repr__() 

Finally:

my solution is to check file mode manually and decide if the referenced file is actually a directory inspired by https://github.com/python/cpython/blob/3.6/Lib/zipfile.py line 391.

def is_dir(fileinfo): hi = fileinfo.external_attr >> 16 return (hi & 0x4000) > 0 

Источник

Оцените статью