Open Python file in a different folder (Explorer)

Asked

Viewed 85 times

0

I would like to know some way to open a file (example, a .csv to do some data analysis) from Windows Explorer. Example:

arquivo = open('arquivo_1.csv','r')

but with the file 'arquivo_1.csv' coming from a different folder from where the file . py (for example) is. In this case, I don’t know if the term is correct, but it would be like importing the file. csv to be used in code, without necessarily writing the file name explicitly.

  • just put the complete path

1 answer

1


There is the medium without "almost dependencies", which is using the parameters, example:

import sys

if len(sys.argv) > 1:
    arquivo = sys.argv[1]
    print(arquivo)
else:
   print('Digite o caminho completo')

Then you’d call it that:

C:\Users\new_g>python C:\Users\new_g\Desktop\teste.py c:\foo\bar\baz.txt

I used the print() just to see the way, just switch to your code.

Of course it is a very simple example and it would be possible to create parameters "with names", to be more intuitive, but it would require a lot more things to implement in the script.

Another way is to use a library that works with "windows" (graphical interface of the operating system), an example is the Tkinter (Tcl/Tk interface).

Before responding, the name of usually this type of window to select files in the manager, such as Windows Explorer, or the Finder (from Mac) is (usually) "Choose file", then an example of this in Tkinter would be:

from tkinter.filedialog import askopenfilename

arquivo = askopenfilename()

print(arquivo)

One detail you might want to adjust in any of the scripts is to use the with along with the open to open the file, something like:

from tkinter.filedialog import askopenfilename
from csv import reader

arquivo = askopenfilename()

try:
    with reader(open(arquivo, 'r')) as read:
        print(read)
except:
    print('Falhou')

But that’s just a suggestion.

Browser other questions tagged

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