makedirs() 给出 AttributeError: 'int' 对象没有属性'rfind'



我正试图创建一个程序,通过为zip文件创建一个目录来保存备份:这是一个字节的python中的一个练习(我将给出完整的例子,这样你们就可以看到他要去哪里了。)示例代码为:

    #! /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

同意@gdlmx的观点,这两个错误都是由变量"today"引起的,该变量是int而不是字符串,因此,您需要简单地将该变量从int更改为字符串,方法是将其放在引号中,如下面的代码行:

today = "14052016"

一旦这样做了,你得到的错误应该逐渐消失。

最新更新