Sam_slo
Sam_slo

Reputation: 141

how to open file in windows with python?

I'm passing the file name trough sys.argv with slashes not backslashes . I'm using os.path.normpath and os.path.join but when trying to open the file I get an exception no such file or directory: and the path is with double backslashes. I'm searching for the solution for hours but nothing works.

I'v tried every tutorial I could find on google and I just keep getting the same problem. I just keep getting double back slashes. I've tried also just hardcoding the path like in example.

filepath = os.path.normpath(os.path.join('D:/dir1/dir2/dir3', 'myfile.txt'))
try:
    my_file = open(filepath, 'w+')
except Exception as e:
    print('Cannot create/open file w+!\n{}'.format(e))

I've need to be able to open the file.

Upvotes: 2

Views: 21824

Answers (3)

jose
jose

Reputation: 1

Add r before the file path for windows.

guests = open(r"C:\folder\guests.txt","w")
initial_guests = ["Bob", "Andrea", "Manuel", "Polly", "Khalid"]

for i in initial_guests:
    guests.write(i + "\n")
    
guests.close()

Upvotes: 0

Sam_slo
Sam_slo

Reputation: 141

In python scripts it works with:

file_path =  os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.ini')

But if I need to build a program with py2exe the __file__ doesn't work and I use:

file_path =  os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'config.ini')

Hope this helps some one.

Upvotes: 2

Muhammad Ibtihaj Tahir
Muhammad Ibtihaj Tahir

Reputation: 636

I would prefer to keep my files in a structured format where my main script will be in the root folder. This approach becomes more generic in a sense that if you try to run the same content on some other system with the different operating system, the path will raise issues.

Example

Project
  |-- main.py
  |-- files
       |--file1.txt
       |--file2.txt

Then you can simply access files by

with open("files/file1.txt", 'w+') as file_object:
    content = file_object.readlines() # Whatever the method

Upvotes: 0

Related Questions