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))
-
1Try printing the path to see if it is showing the path or not.CodeIt– CodeIt2019年07月25日 13:51:27 +00:00Commented Jul 25, 2019 at 13:51
-
1Please elaborate "doesn't work".bereal– bereal2019年07月25日 13:52:50 +00:00Commented Jul 25, 2019 at 13:52
2 Answers 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!
Comments
readline leaves the trailing linefeed in the line. Use:
path = lines[0].strip()