Home > other >  Why can't i create a folder when he doesn't exist?
Why can't i create a folder when he doesn't exist?

Time:06-23

i 'm trying to make a for loop who browse files in a specific directory while creating a folder if he doesn't exist with this solution. here is the code:

import ftputil

host=ftputil.FTPHost('x.x.x.x',"x","x")   #connecting to the ftp server
mypathexist='./CameraOld' (he is here: /opt/Camera/CameraOld
mypath = '.' #it put you in /opt/Camera (it's the default path configured)
host.chdir(mypath)
files = host.listdir(host.curdir)


for f in files: #i browse the files in my folders
    if f==mypathexist: #if a file is named CameraOld (it's a folder)
        isExist=True
        break
    else: isExist=False #if 0 file are named like it 
print(isExist)

if isExist==False: #if the file doesn't exist 
    host.mkdir(mypathexist) #create the folder
else:
print("ok")

The problem is that isExist is always false so the script try to create a folder who is already created. And i don't understand why.

Here's the output:

False #it's the print(isExist)

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/ftputil/host.py", line 695, in command
    self._session.mkd(path)
  File "/usr/lib/python3.10/ftplib.py", line 637, in mkd
    resp = self.voidcmd('MKD '   dirname)
  File "/usr/lib/python3.10/ftplib.py", line 286, in voidcmd
    return self.voidresp()
  File "/usr/lib/python3.10/ftplib.py", line 259, in voidresp
    resp = self.getresp()
  File "/usr/lib/python3.10/ftplib.py", line 254, in getresp
    raise error_perm(resp)
ftplib.error_perm: 550 CameraOld: file exist

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/user/Bureau/try.py", line 16, in <module>
    host.mkdir(mypathexist)
  File "/usr/local/lib/python3.10/dist-packages/ftputil/host.py", line 697, in mkdir
    self._robust_ftp_command(command, path)
  File "/usr/local/lib/python3.10/dist-packages/ftputil/host.py", line 656, in _robust_ftp_command
    return command(self, tail)
  File "/usr/local/lib/python3.10/dist-packages/ftputil/host.py", line 694, in command
    with ftputil.error.ftplib_error_to_ftp_os_error:
  File "/usr/local/lib/python3.10/dist-packages/ftputil/error.py", line 195, in __exit__
    raise PermanentError(
ftputil.error.PermanentError: 550 CameraOld: file exist
Debugging info: ftputil 5.0.4, Python 3.10.4 (linux)

CodePudding user response:

I would bet your mypathexist is not correct. Or the other way around, your file list, doesn't hold the strings in that condition you assume it does.

Take a look at your condition by hand. Print out f in your loop. Is it what you would expect to be?

In the end, Python is simply comparing Strings.

  • Related