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

时间:2016-05-14 22:21:53

标签: python

我试图创建一个程序,通过为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' 

此追溯在模块中引用了行,所以现在我知道我遇到了麻烦。是否有可能变量&#34;今天&#34;仍然是这两个错误的核心?有没有更好的方法来定义今天,以便不会拉出这么多的错误或有更好的方法来检查和创建一个子目录?如果你们在他的例子中发现更多错误,请不要纠正它们。我相信我很快就能找到它们。 :)感谢您的帮助。

注意:我正在运行ubuntu 14.04 LTS并使用python 3

1 个答案:

答案 0 :(得分:0)

同意@gdlmx,这两个错误都来自您的变量&#34;今天&#34;这是一个int而不是一个字符串,因此,您需要通过将该变量放入引号中来简单地将该变量从int更改为字符串,如下面的代码行所示:

today = "14052016"

一旦完成,你所得到的错误就会逐渐消失。