Reputation: 125
I am trying to get filenames that are written line by line in a text file. I have tried using the following code to return a name for each line in a variable called filenames. When I try to print the filenames variable to assure it has been properly retrieved, an error occurs stating the (filenames) is not defined. I also made a test variable to check if it is just not reading the lines correctly but the same error occurs. Any ideas?
def read(textFile):
filenames = []
test = "test"
with open ("C:\\xampp\\htdocs\\test.new\\multiUploadTest\\var.txt", "r+") as myfile:
for line in myfile:
filenames.append(line)
print test
print (filenames)
return (filenames, test)
print (test)
print (filenames)
Upvotes: 0
Views: 608
Reputation: 21
You are getting that error "C:\xampp\htdocs\test.new\multiUploadTest\var.txt", "r+" - because of the double \ - so the file can not be read.
This error has nothing to do with the code it has to do with file location, do a test, copy the file in the same folder as the code and then point the with open() to that folder, or just drop the \ and use a single \
Upvotes: 0
Reputation: 122024
You need to do something with the values you return
, e.g.:
test, filenames = read("testing.txt")
print(test)
print(filenames)
Names in Python are just references to objects; returning test
and filenames
passes the objects those names reference back to the calling function, but doesn't mean that the same names will automatically be available. In fact, you can name them something completely different in the calling function and everything will still work:
foo, bar = read("testing.txt")
print(foo)
print(bar)
Upvotes: 2
Reputation: 4176
test
and filenames
are only available inside your function. so you need to either call the function and assign the values to variable outside the function and then use them, or you could declare them as global in which case you don't need to return them.
So, you could either do this:
def read(textFile):
filenames = []
test = "test"
with open ("C:\\xampp\\htdocs\\test.new\\multiUploadTest\\var.txt", "r+") as myfile:
for line in myfile:
filenames.append(line)
print test
print (filenames)
return (filenames, test)
filenames, test = read(your_filename)
print filenames, test
or you could the following:
def read(textFile):
global filenames, test
filenames = []
test = "test"
with open ("C:\\xampp\\htdocs\\test.new\\multiUploadTest\\var.txt", "r+") as myfile:
for line in myfile:
filenames.append(line)
print test
print (filenames)
read(your_filename)
print filenames, test
Upvotes: 0