|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
How to zip a file?
Hello All!
I had this idea about a script that would come in handy for me and maybe for somebody else. At this stage I am still learning and this will be beyond my knowledge. If somebody can help me out by showing how to do this? What i want is to search for all files in all directories and if found a file ending in txt extention RAR(winrar) this file and then delete the original file. Thanks Random |
|
#2
|
||||
|
||||
|
You can use os.path.walk() to walk through a directory tree, and os.path.splitext() to get the extension. See the docs for the os.path module here: http://web.pydoc.org/2.1/posixpath.html
To zip the file up, you'll probably need the zipfile module: http://web.pydoc.org/2.2/zipfile.html Finally, to remove the old file, use os.unlink(): http://web.pydoc.org/2.1/os.html
__________________
Up the Irons What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home. "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest Down with Sharon Osbourne Puzzle of the Month solved by Keath and KevinADC, superior perl programmers of the month Looking for a perl job with kick-*** programmers in a well-known NASDAQ listed tech company with branches in the US and Europe? We're hiring. PM me for details. Requirements |
|
#3
|
|||
|
|||
|
Thanks Scorpions4ever!
I have started doing what you sudgested up until the actual process of ziping the the file which did not work. Any advice? Code:
import os.path, zipfile
def action(arg, dirname, file_list):
for file in file_list:
split = os.path.splitext(file)
if (split)[1] == '.txt':
z = zipfile.ZipFile(split[0]+ '.zip', "w")
z.close()
root = 'D:/new folder'
arg = None
os.path.walk(root, action, arg)
|
|
#4
|
||||
|
||||
|
You might find os.walk() easier to work with than os.path.walk() as well as being faster
, also you can check the file extension for the filenames much easier using the str.endswith method i.e.Code:
if file.endswith('.txt'):
...
do whatever with the file
...
Mark. |
|
#5
|
||||
|
||||
|
arg you read my mind!! Mr you told me that built in func good you told him as well :P
__________________
IE QUOTE | PHP Manual | Google | C/C++ Compiler | Linux Tutorials | General Stuff Game Dev |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > How to zip a file? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|