I have a function that parses a file into a list. I\'m trying to return that list so I can use it in other functions.
def splitNet():
network = []
f
Variables cannot be accessed outside the scope of a function they were defined in.
Simply do this:
network = splitNet()
print network
Your function is returning a list so you have to assign it to a variable and than try to print it.
network = splitNet()
print network
For example
>>> def mylist():
... myl = []
... myl.append('1')
... return myl
...
>>> my_list = mylist()
>>> my_list
['1']
>>>
L=[1, 2, 3]
def rl(l):
return l
[*ll] = rl(L) # ll is in a list
ll
# >>> [1, 2, 3]
*t, = rl(L) # ll is in a tuple
t
# >>> [1, 2, 3]
If you want to return an item or list from a definition, you could define it before hand and use it as a variable during the initial writing of said definition. Unless it has to be defined within the definition. In this case you won't need to write in a return command at the end.
network = []
def splitNet(network):
for line in open("/home/tom/Dropbox/CN/Python/CW2/network.txt","r").readlines():
line = line.replace("\r\n", "")
line = string.split(line, ',')
line = map(int, line)
network.append(line)
print network # Will print the list you've appended. But it is now a usable object.
Have you actually called the function yet? This works fine (in the Python interpreter)
>>> def f():
... network = []
... network.append(1)
... network.append(2)
... network.append(3)
... return network
...
>>> network = f()
>>> print network
[1, 2, 3]
The names of variables in a function are not visible outside, so you need to call your function like this:
networks = splitNet()
print(networks)
A couple of other notes:
readlines
; the function itself is an iterator.with
statement.str.split
, which is more readable and easier to understand than string.split
.In summary, this is how your code should look like:
import csv
def splitNet():
with open("/home/tom/Dropbox/CN/Python/CW2/network.txt") as nf:
for line in csv.reader(nf, delimiter=','):
yield map(int, line)
network = list(splitNet())
print (network)