У меня не работает пример программы из книжки.
import os
import time
source = ['"C:\My Documents"', 'C:\Code']
target_dir = 'C:\Backup'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
print(zip_command)
if os.system(zip_command) == 0:
print('Резервная копия успешно создана в', target)
else:
print('Создание резервной копии НЕ УДАЛОСЬ')
Вывод всегда один и тот же:
zip -qr C:Backup20180914031536.zip "C:My Documents" C:Code Создание резервной копии НЕ УДАЛОСЬ
только при указании не существующих директорий вывод немного меняется.
Не пойму в чем проблема. C:Program FilesGnuWin32bin
к системной переменной окружения PATH
я вроде добавил, всё вроде должно работать.
Windows 10, Python 3.6
C:UsersFrost>zip -qr C:Backup20180917121916 . -i .zip C:My Documents C:Code
zip I/O error: No such file or directory
zip error: Could not create output file (C:/Backup/20180917121916.zip)
-@Alex
insolor
44.2k15 золотых знаков52 серебряных знака92 бронзовых знака
задан 14 сен 2018 в 0:24
5
Раз код не выпадает в исключение — значит, утилита zip отрабатывает корректно. Это уже хорошо.
Попробуй прямо в системе открыть консоль (cmd) и в ней выполнить получившуюся команду (zip -qr C:Backup20180914031536.zip "C:My Documents" C:Code
). Возможно, zip выведет сообщение об ошибке, по которому можно будет понять, что же ему не понравилось)
UPD.: Судя по ошибке «не является внутренней или внешней командой» — я был неправ, утилита ZIP всё-таки не отрабатывает: скорее всего, интерпретатор просто не может её найти. Варианта решения я вижу два:
-
Разобраться, где лежит исполняемый файл zip.exe, и добавить этот каталог в PATH. После этого команда в консоли (cmd) должна начать выполняться — а после этого должна заработать и программа на Python.
Кстати, тут ещё момент: после изменения PATH интерпретатор лучше перезапустить (прямо закрыть окно и запустить заново), а то переменные среды могут не обновиться. -
(грязный хак) Просто прописать в
zip_command
вместоzip
полный путь к архиватору (скажем,C:\Program Files\GnuWin32\bin\zip.exe
).
Если оставить только первый файл — архив создаётся? Как выглядит zip_command
?
- Если заменить source =
['"C:\My Documents"', 'C:\Code']
наsource = ['"C:\My Documents"']
— какой будет результат? - Перед сообщением «Создание резервной копии НЕ УДАЛОСЬ» скрипт должен печатать команду, которая будет выполнена. В изначальном примере скрипт печатал следующее:
zip -qr C:Backup20180914031536.zip "C:My Documents" C:Code
.
Как выглядит эта строка сейчас?
ответ дан 14 сен 2018 в 2:07
AlexAlex
3311 серебряный знак7 бронзовых знаков
target_dir = ‘C:Backup’
Вам необходимо ЗАРАНЕЕ создать данную директорию.
ответ дан 9 мар 2019 в 15:56
Все легче чем ты думаешь:
1) проверь если в в C:GnuWin32binzip.exe , если ты там сам файл zip.exe.
Я сам с этой проблемой столкнулся и его не было там. Далее ;
2) в строке zip_command = "zip -qr {0} {1}".format(target, ' '.join(source))
исправь на : zip_command = 'zip -r {0} {1}'.format(target, ' '.join(source))
;
3)Посмотри пути к файлу и путь к папке куда идет backup. Вот как у меня пути выглядят
source = ['C:\Users\nsmex\Desktop\backup']
target_dir = 'C:\Users\nsmex\Desktop\test'
ответ дан 18 мар 2019 в 19:53
создай целевую папку C:Backup. она у тебя не создана или, если создана, укажи путь к ней
ответ дан 30 мар 2020 в 17:06
2
10 More Discussions You Might Find Interesting
1. Shell Programming and Scripting
Zipping file issues
Hi All,
I am trying to zip a file but facing the issue.
I have three zip files.
a_1.zip
a_2.zip
c.zip
I want to add a_1.zip and a_2.zip to c.zip
Code:
###############
for i in a*.zip; do
printf «%sn» «$i»
done | zip -@ c.zip (2 Replies)
Discussion started by: weknowd
2. UNIX for Dummies Questions & Answers
Help With zipping a file
Hi
I need to zip a file and move it into another folder along with the timestamp. The orginal file must be removed from the source directory
Source :
folder1/source12.txt
folder2
After zipping
Folder1/Folder2/source12.zip
Any help will be greatly appreciarted
… (5 Replies)
Discussion started by: akshay01987
3. UNIX for Dummies Questions & Answers
Zipping the file when moving
Hi,
I have a file a.txt, I am moving the file from my source location (/root/onw/src) to target folder(root/byl/src). My target folder has already a file by name a.txt..,while moving can I see if this file a.txt is existing then move it to archive folder(/root/byl/arc) zip and add time stamp to… (2 Replies)
Discussion started by: shruthidwh
4. Shell Programming and Scripting
grep a file and zipping it
Hi,
In my process iam creating a temporary filelist with filename and date(yyyy-mm-dd format).I need to search file for a date and zip.
Below command is giving the filename ,can someone helpme how to add the zip or gzip command to this statement.
grep 2010-11-11 filelist.log | awk… (1 Reply)
Discussion started by: swathich
5. Shell Programming and Scripting
Zipping of file in a different directory
Hi,
I am having some problem with a shell script which zip some files. For zipping I have used the following command:
find . -name «Test_*» -mtime 0 | zip Test_$(date +»%Y%m%d») -@
I have kept the script in /home/abc directory. It is creating the zip file within the same directory where i… (2 Replies)
Discussion started by: abhishek_510
6. Shell Programming and Scripting
zipping a directory when the file count is over $X
Hiya,
I’ve been plugging away at this script and I cant get it to behave as I need.
first off it fails to adhere to the conditions of the file limit, and zips the directory regardless of the file count and secondly, but less important it zips up the entire path not just the directory I’m… (2 Replies)
Discussion started by: orionrush
7. Solaris
Error while zipping files
I was trying to remove & archive all the files in the current directory and embed them into the zip file, i mean i don’t want to list the files any more after zipping those files. For this i wrote the following code though operation was succeeded zipping all the files and creating a zip file i am… (2 Replies)
Discussion started by: Ariean
8. Shell Programming and Scripting
Script for zipping a file
HI,
I want a script which creat a zip file folder of files older than 15 days…….
please help me on this……….. (4 Replies)
Discussion started by: jayaramanit
9. UNIX for Advanced & Expert Users
Help me While zipping the file
Hi ,
I have written code which will ask the subject,body of the mail, attachment and mail id of the receipient.
Code will pick up 4 files zip it. It will zip all the files and then post the mail to the receipient. While zipping the file i am getting error. Can anyone help me with this.
… (7 Replies)
Discussion started by: Jolly
Similar questions have been asked, but I couldn’t find exactly what I’m looking for. Basically, I have a large directory with subdirectories and many files, and I want to go into each directory and subdirectory recursively, and zip each file individually. I found this solution, but it’s not quite what I want:
find . -type f -execdir zip '{}.zip' '{}' ;
Source
This outputs the zip files into the directory they came from. However, I want the zip files in a completely separate directory, but with the same directory structure, with only the resulting zip files. Can anyone help with this?
asked Mar 15, 2017 at 17:52
2
You can pre-pend a relative path to the location of the zip file as:
find . -type f -exec zip -D '../zipdir/{}.zip' '{}' ;
If needed, to create the directory structure you can do:
find . -type d -exec mkdir -p '../zipdir/{}' ;
answered Mar 15, 2017 at 21:27
Stephen RauchStephen Rauch
3,00110 gold badges23 silver badges26 bronze badges
2
If you’re not married to zip files, you could just create a squashfs image of the whole directory tree in question that’s mountable too (no opening & looking in specific zip files to see what’s there). It may have better compression too, since it looks at the entire tree together, more like a «solid» archive, instead of lots of individual zip files.
Basically you just need the squashfs-tools
package (that’s what it’s called in Debian/Ubuntu, maybe a different name in different linux families), then:
mksquashfs /some/directory archive.squashfs
and to mount/view/browse it:
mount archive.squashfs /mnt/mountpoint -t squashfs
the -t flag may even be optional, mount is really good at automatically figuring out types. Shouldn’t need the -o loop
flag either, but try it just in case it’s needed.
See http://tldp.org/HOWTO/SquashFS-HOWTO/creatingandusing.html or just search for how to use squashfs.
answered Mar 17, 2017 at 6:28
Xen2050Xen2050
13.5k4 gold badges23 silver badges42 bronze badges
- Forum
- The Ubuntu Forum Community
- Ubuntu Specialised Support
- Development & Programming
- Programming Talk
- [SOLVED] ‘Byte of Python’ backup script question
-
[SOLVED] ‘Byte of Python’ backup script question
I’ve recently started learning Pyhton (my first programming language actually) using the ‘Byte of Python’ guide by Swaroop. I’m currently at the stage where he walks us through writing a backup script and I’ve run into one small problem. Here is the code:
Code:
import os import time # 1. The files and directories to be backed up are specified in a list. source = ['/home/bandd/Python Scripts/'] # 2. The backup must be stored in a main backup directory target_dir = '/media/Backup Bitch/BandD Backup/bandd/Python Scripts/' # 3. The files are backed up into a zip file # 4. The name of the zip archive isthe current date and time target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command = "zip -vr '%s' %s" % (target, ' '.join(source)) #Run the back up if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED!'
The target_dir is an external USB HDD, but I get an I/O error in the zip program that says:
Code:
zip I/O error: No such file or directory zip error: Could not create output file (/media/Backup Bitch/BandD Backup/bandd/Python Scripts/20080321212955.zip) Backup FAILED!
If I change the target_dir to my home folder, it works fine. I even copied and pasted the mount point from the drive properties into the script after it failed the first time, with no luck. Is there something special I have to do to allow this python script access to the external hard drive? Just curious.
Thanks,
Dustin
Registered Ubuntu User #20847
-
Re: ‘Byte of Python’ backup script question
When working with strings, you need to escape the backslash.
«» should be «\».
Also, you should use methods of the os.dir if you are interested in portability, if it’s only for you, then go ahead. And try to check if folders/files exist before doing anything, it’s always a good practice.
Last edited by Can+~; March 22nd, 2008 at 08:58 PM.
«Just in terms of allocation of time resources, religion is not very efficient. There’s a lot more I could be doing on a Sunday morning.«
-Bill Gates
-
Re: ‘Byte of Python’ backup script question
Thanks for the reply Can+~
It helped me see my error. I’m learning to write bash scripts at the moment as well, and I forgot that Python handles spaces just fine with out the need of an escape. So I changed the path in the script to
Code:
/media/Backup Bitch/BandD Backup/bandd/Python Scripts
and it worked.
Also thanks for the tip on os.dir. Much appreciated!
Registered Ubuntu User #20847
-
Re: [SOLVED] ‘Byte of Python’ backup script question
you can check out raw strings.. Its also in the tutorial. please read the tutorial.
-
Re: ‘Byte of Python’ backup script question
Originally Posted by Can+~
When working with strings, you need to escape the backslash.
«» should be «\».
Also, you should use methods of the os.dir if you are interested in portability, if it’s only for you, then go ahead. And try to check if folders/files exist before doing anything, it’s always a good practice.
Hi,
I also using the same but the prob I am getting is that when zip command zip files, it takes full path like /home/user/Desktop/Backup/.
I also tried to use gllo.glob but that also just include files form main folder and subfolders but no file from subfolders.
Similarly I used os.walk(source) but in that one also it takes all files form main folders and subfolders and then write to .zip file without directory structure.
Can you please suggest if I can use zip command to create actual Folder path only or glob.glob so that it include subfolder’s files also or os.walk for real directory structure. Thanks in advance.
Regards,
Akash…