0

when I simply write the path of my folder in a variable it works, but when I read the path in simple txt files it doesn't work Example :

path = "path to a folder" it works

but when I use :

path = lines[0] it doesn't works

My application go read the first line of txt file where my path is stocked and then it should stock it in the path variable.

I tried to see if the path was read correctly and yes, if I print the path it was always good but it doesn't work.

txt=open('/Users/patrick/Desktop/config.txt','r')
lines = txt.readlines()
path = lines[0]
files = []
for r, d, f in os.walk(path):
 for file in f:
 files.append(os.path.join(r, file))
Harsha Biyani
7,28810 gold badges42 silver badges64 bronze badges
asked Jul 25, 2019 at 13:49
2
  • 1
    Try printing the path to see if it is showing the path or not. Commented Jul 25, 2019 at 13:51
  • 1
    Please elaborate "doesn't work". Commented Jul 25, 2019 at 13:52

2 Answers 2

2

You need to strip white spaces and \n new line character because readlines returns lines including \n.

txt=open('/Users/patrick/Desktop/config.txt','r')
lines = [line.strip() for line in txt.readlines()]
path = lines[0]
files = []
for r, d, f in os.walk(path):
 for file in f:
 files.append(os.path.join(r, file))

Instead of using readlines, you can use read and split using \n character.

text = open('/Users/patrick/Desktop/config.txt','r').read()
lines = text.split("\n")
path = lines[0]
files = []
for r, d, f in os.walk(path):
 for file in f:
 files.append(os.path.join(r, file))

Hope it helps!

answered Jul 25, 2019 at 13:52
Sign up to request clarification or add additional context in comments.

Comments

0

readline leaves the trailing linefeed in the line. Use:

path = lines[0].strip()
answered Jul 25, 2019 at 13:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.