How do i open a python path?

Suppose my python code is executed a directory called main and the application needs to access main/2091/data.txt.

how should I use open[location]? what should the parameter location be?

I found that below simple code will work.. does it have any disadvantages?

file = "\2091\sample.txt"
path = os.getcwd[]+file
fp = open[path, 'r+'];

Neuron

4,5854 gold badges32 silver badges53 bronze badges

asked Aug 23, 2011 at 18:24

4

With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself.

If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__ to help you out here. __file__ is the full path to where the script you are running is located.

So you can fiddle with something like this:

import os
script_dir = os.path.dirname[__file__] #

Chủ Đề