gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:37:53 25 4
gpt4 key购买 nike

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

如果目录存在于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com