2016-05-14 22 views
0

我試圖創建一個程序,通過爲zip文件創建一個目錄來保存備份:這是一個練習,從一個字節的python(我要給予充分的例子,這樣你們可以看到他是怎麼回事。) 的示例代碼:makedirs()給AttributeError:'int'對象沒有屬性'rfind'

#! /usr/bin/env python3 
    import os 
    import time 


    # 1. The files and directories to be backed up are specified in a list. 
    source = ['~/Desktop/python'] 

    # 2. The backup must be stored in a main backup directory 
    target_dir = '~/Dropbox/Backup/' # Remember to change this to what you'll be using 

    # 3. The files are backed up into a zip file. 
    # 4. the name of the zip archive is the current date and time 
    target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') +'.zip' 
    now = time.strftime('%H%M%S') 

    # Create the subdirectory if it isn't already there. 
    if not os.path.exists(today): 
     os.mkdir(today) # make directory 
     print('Successfully created directory', today) 

    # The name of the zip file 
    target = today + os.sep + now + '.zip' 

    # 5. We use the zip command to put the files in a zip archive 
    zip_command = "zip -qr {0} {1}".format(target, ' '.join(source)) 
    print(zip_command) 
    # Run the backup 
    if os.system(zip_command) == 0: 
     print('Successful backup to', target) 
    else: 
     print('Backup FAILED') 

這拉起錯誤:

Traceback (most recent call last): 
     File "backup_ver2.py", line 23, in <module> 
     os.mkdir(today) # make directory 
    TypeError: mkdir: illegal type for path parameter 

我的解決辦法:

import os 
    import time 

    today = 14052016 # I set today as a string to solve a previous issue. 

    ..... 
    # Create the subdirectory if it isn't already there. 
    if not os.path.exists(today): 
     os.makedirs(today, exist_ok=True) # make directory 
     print('Successfully created directory', today) 

這給錯誤:所以現在我知道我遇到了麻煩

Traceback (most recent call last): 
     File "backup_ver2a.py", line 23, in <module> 
     os.makedirs(today, exist_ok=True) # make directory 
     File "/usr/lib/python3.4/os.py", line 222, in makedirs 
     head, tail = path.split(name) 
     File "/usr/lib/python3.4/posixpath.py", line 103, in split 
     i = p.rfind(sep) + 1 
    AttributeError: 'int' object has no attribute 'rfind' 

這回溯引用了線的模塊中。變量「今日」是否可能仍然是這兩個錯誤的核心?有沒有更好的方法來定義今天,以避免這麼多的錯誤,或者有更好的方法來檢查和創建一個子目錄?如果你們在他的例子中注意到更多的錯誤,請不要糾正它們。我相信我很快就會找到他們。 :) 謝謝你的幫助。

注:我運行Ubuntu 14.04 LTS和使用Python 3

+1

'today = 14052016'這與您所說的「一串」相矛盾。字符串需要引用 – gdlmx

回答

0

與@gdlmx達成一致,從變量「今天」,這是一個int,而不是一個字符串,從而導致這兩個錯誤,你需要簡單通過將其放入報價,像下面的代碼行作出該變量從int一個字符串的變化:

today = "14052016" 

一旦做到這一點你要應消失的錯誤。