Read file in previous python folder

Asked

Viewed 765 times

1

so I’m wanting to save a python file in a folder previous to the one running the script

ex:my script is in the /app/controllers/script.py directory i want to put the file I will create in the folder: /app/statics/download/Arq.zip

code:

import os.path
basedir = os.path.abspath(os.path.dirname(__file__))

localsalvar = basedir + '../statics/downloads/'
with open(localsalvar + id + '.zip', "w") as f:
    f.write(cvcompacto)#criando o arquivo .zip

He is unable to move up the folder, thinking that '/.. /' is a folder

FileNotFoundError: [Errno 2] No such file or directory: '/root/extrator/app/controllers../statics/downloads/9837509907462335.zip'
  • 1

    Lucas, you have tried to put only the value '.. /Static/downloads/' without concatenating basedir?

  • Yes gives the same problem Filenotfounderror: [Errno 2] No such file or directory: '.. /statics/downloads/'

2 answers

1


On the path of the error message

'/root/extrator/app/controllers../statics/downloads/9837509907462335.zip'

is apparently missing a directory separator (bar) between 'controllers' and '..' - your system is looking for a folder called 'controllers..', that probably doesn’t exist.

Modify the line

localsalvar = basedir + '../statics/downloads/'

for

localsalvar = basedir + '/../statics/downloads/'

or better yet, use os.path.join for your code to automatically add tabs (working for both Windows and Mac and Linux):

localsalvar = os.path.join(basedir, '..', 'statics', 'downloads')
  • Then it continues the same error, it is understanding that '.. ' is the name of a folder python
FileNotFoundError: [Errno 2] No such file or directory: '/root/extrator/app/controllers/../statics/downloads/9837509907462335.zip'


  • Please confirm that the directory '/root/extrator/app/statics/downloads/ exists on your computer. The path seems valid, so the only way to generate this error is if the directory does not exist.

0

In Python, to move a file to another directory just use the shutil module:

import shutil
shutil.move("cvcompacto", "/../statics/downloads/")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.