python - 在Python中更改目录,不起作用

标签 python

我正在努力实现这个功能:

如果目录存在于 FTP 中,则更改它们,如果不存在,则创建它们并将目录更改为该目录

def directory_exists(self, directory_name):
        if directory_name in ftp.nlst():
            self.change_directory(directory_name)
        else:
            self.make_directory(directory_name) and self.change_directory(directory_name)

函数调用:

def make_directory(self, directory):
        if ftp.mkd(directory):
            self.log_message("Directory {0} created successfully".format(directory))
            return True
        else:
            self.log_message("Failed creating directory")
            return False

def change_directory(self, directory):
        if ftp.cwd(directory):
            self.log_message("Current Directory is now {0}".format(ftp.pwd()))
        else:
            self.log_message("Can't change Directory")

如果给定任何新目录作为参数,则此代码当前有效,并且如果给出现有目录,则会出现此回溯。

Traceback (most recent call last):
  File "C:/Users/Ajay/PycharmProjects/database/config.py", line 17, in <module>
    ftp_obj.directory_exists(directory)
  File "C:\Users\Ajay\PycharmProjects\database\ftp.py", line 51, in directory_exists
    self.make_directory(directory_name) and self.change_directory(directory_name)
  File "C:\Users\Ajay\PycharmProjects\database\ftp.py", line 34, in make_directory
    if ftp.mkd(directory):
  File "C:\Python27\lib\ftplib.py", line 568, in mkd
    resp = self.sendcmd('MKD ' + dirname)
  File "C:\Python27\lib\ftplib.py", line 244, in sendcmd
    return self.getresp()
  File "C:\Python27\lib\ftplib.py", line 219, in getresp
    raise error_perm, resp
ftplib.error_perm: 550 Can't create directory: File exists

我的代码函数调用逻辑:

directory = '/new'
ftp_obj.directory_exists(directory)

最佳答案

我通过一些小技巧解决了这个问题。

def directory_exists(self, directory_name):
        new_dir_name = directory_name.strip("/")
        if new_dir_name in ftp.nlst():
            self.change_directory(directory_name)
        else:
            self.make_directory(directory_name)
            self.change_directory(directory_name)

现在,一切正常。

关于python - 在Python中更改目录,不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21192648/

相关文章:

python - 在 Python 2.7 中获取列表长度作为字典中的值

python - 自动替换网页图像中的 Logo

python - 统计一个单词中不同字符的个数

python - 如何修复 python3、django2 中的 "unexpected token ' ]' "错误?

python - Python中的表达式和语句有什么区别?

python - 为什么 isinstance([1, 2, 3], List[str]) 的计算结果为真?

python - 如何按行长度对 pandas 数据框进行排序

python - 导入 scipy.stats 时,获取 'ImportError: DLL load failed: The specified procedure could not be found'

python - 合并数据框中的重复列

python - 如何将 BeautifulSoup.ResultSet 转换为字符串