I’ve been searching online for a while now and can’t seem to find anything. I’m basically learning a few languages and I am just trying to recreate a program in different languages.
def read_one_file():
f = open('C:\Python27\inventory.dat', 'r')
invid = f.readline()
stock = f.readline()
published = f.readline()
price = f.readline()
invtype = f.readline()
title = f.readline()
author = f.readline()
return invid, stock, published, price, invtype, title, author
read_one_file()
print "Update Number In Stock"
print "----------------------"
print "Item ID: ", invid
Basically I’m trying to read in a file, absorb the data into variables then pass those variables to the main(class?). When I return them they’re still not able to be printed. When I initialize them outside of read_one_file they still don’t return the right thing.
You need to store the results of read_one_file() somewhere. What you’re really
doing with your return statement is creating a tuple of the results. You then
have to unpack that tuple when you call read_one_file. Here is an example:
This syntax is performing something called “pattern matching” and what it does
is break up the tuple that read_one_file returns and gives names to each of
element in it. I added the parenthesis here to make it clearer that
read_one_file is returning a tuple, but you could just as easily write it like
this:
That’s all well and good, but really, this is sort of a bad way to return things
from your function. If you have a lot of variables you want to return from a
function like this, a dict is probably a better way to go. Also, you’ll
probably want to use a with statement to ensure your file is closed and cleaned
up properly once you’re done with it. Here is what your code would look like
using that strategy:
Edit: I changed the code above to use .strip(), since (as @NiklasB. pointed out), newlines are still included with just readline.