How do I read a filepath from a text file using Python?

Question:

I am currently trying to write a simple python script that opens a folder or a list of folders using filepaths that I have written down on my text file.

import os

with open('filepaths.txt') as f:
    [os.startfile(line) for line in f.readlines()]

My issue is that whenever I run this code, python reads the lines as its non-raw form. The backslashes are doubled, and there is a new line "n" in every string.

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'D:\Nitro\Downloadsn'

I have attempted to solve this problem using repr() on the variable. Instead of removing the backslash, it was doubled even further.

import os

with open('filepaths.txt') as f:
    [os.startfile(repr(line)) for line in f.readlines()]
FileNotFoundError: [WinError 2] The system cannot find the file specified: "'D:\\Nitro\\Downloads\n'"

I have also attempted to use the string replace function to replace "" with "". It did not work.

Asked By: OmniMaxim

||

Answers:

The readlines method reads the file correctly, with the trailing newline character in each line preserved. You just need to strip the newline character from the string before using it as a path name, which is typically done with the str.rstrip method:

for line in f: # no need to use the readlines method for iteration
    os.startfile(line.rstrip())

The path name in the error message you included in the question contains double backslashes because it is displayed with the repr function, with backslashes escaped already, not because the path names are read incorrectly.

Answered By: blhsing
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.