I'm having trouble creating a function with one parameter that reads from a file and then creates and returns a dictionary based on what's in the file.

And example of whats in the file:

115     139-28-4313     1056.30
135     706-02-6945      -99.06
143   595-74-5767     4289.07
155     972-87-1379     3300.26

What i have:

open('balance.txt', 'r')

    for line in ('balance.txt'):
	acct, SSN, balance = line.split()
	balfilename[acct] = int(SSN, balance)

An error that i'm getting is: <_io.TextIOWrapper name='balance.txt' mode='r' encoding='US-ASCII'> What am i doing wrong and what exactly is the error telling me?

Recommended Answers

All 47 Replies

Since you did not include the entire error message we have to guess as to which line it is referring to (and that is quite possibly an information message, not an error message), so adding a print statement after the for() loop is the obvious place to start. A tutorial for opening files.

for line in ('balance.txt'):
    ## print for testing
    print "line =", line
    acct, SSN, balance = line.split()
    balfilename[acct] = int(SSN, balance)

Note: an error message looks like this

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'balance.txt'

Since you did not include the entire error message we have to guess as to which line it is referring to (and that is quite possibly an information message, not an error message), so adding a print statement after the for() loop is the obvious place to start. A tutorial for opening files.

for line in ('balance.txt'):
    ## print for testing
    print "line =", line
    acct, SSN, balance = line.split()
    balfilename[acct] = int(SSN, balance)

Note: an error message looks like this

You're correct. I don't believe that it was an error message. The error message that I'm receiving though is as follows...

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    type(fname)
NameError: name 'fname' is not defined
balfilename={}
    fname=open("balance.txt",'r')
    for line in fname.readlines():
	    balfilename.append(fname)
    fname.close()
    print(balfilename)

-Are you sure the file is in the same directory as the program calling it?

-you don't append to a dictionary, you can append to a value if that value is a list or you can update a dictionary.

-if you could you're trying to add the file the dictionary for each line in the file.

-note that read lines makes a list of the lines in the file. "try it out"

-stop doing what you're doing.

-think about how you know the file is formatted and keep in mind the the structure of a dictionary entry is {key:value}

-check out woooee's example, it's good, I like it, no, I love it; if it were coffee, I'd drink it.

File "<pyshell#20>", line 1, in <module>

Don't use a shell as you can only key in one line at a time. Use IDLE which comes with Python, or a text editor to key in the program, and then save as a file that you can run and/or modify. And once again, print so you know what you are adding, in this case it is "fname".

print fname
    balfilename.append(fname)

Don't use a shell as you can only key in one line at a time. Use IDLE which comes with Python, or a text editor to key in the program, and then save as a file that you can run and/or modify. And once again, print so you know what you are adding, in this case it is "fname".

print fname
    balfilename.append(fname)

The only reason i'm using shell is bc what i'm trying to create is a function with a single parameter, but i wanna check to see if the code that i'm using in the function is actually doing what i want it to do before actually creating the function with a return statement.

def customer_dictionary(balfilename):
    balfilename={}
    fname= open('balance.txt', 'r')
    for line in fname.readlines():
        print(fname)
        balfilename.append(fname)
        fname.close()
        return balfilename

Is there a way to be able to tell if the function will work or not before going to the next step, which is another function with two parameters, but it's main objective is to update the information that was read in the previous function?

You should not retrun the name, you should return dictionary, you have very misleading name. The call parameter has no meaning as you empty the parameter immediately at first line of the function and use it for empty dictionary and after in line 6 use it as list with append, not as dictionary like it was initialized, causing error.

You should not retrun the name, you should return dictionary, you have very misleading name. The call parameter has no meaning as you empty the parameter immediately at first line of the function and use it for empty dictionary and after in line 6 use it as list with append, not as dictionary like it was initialized, causing error.

Is this on the right track?? The function should open balfilename for reading. It should then create a dictionary with key:value pairs in which the key is the bank account number of a customer, and the value associ- ated with a key is a list containing the SSN and the account balance for that customer. The function must return the dictionary.

115     139-28-4313     1056.30
135     706-02-6945      -99.06
143   595-74-5767     4289.07
155     972-87-1379     3300.26
def customer_dictionary(balfilename):
    balfilename= open('balance.dat', 'r')
    for line in balfilename.readlines():
        print(balfilename)
    balfilename.close()
    custome_dict={}
    return customer_dict

No.

No.

def customer_dictionary(balfilename):
    balfilename= open('balance.dat', 'r')
    customer_dict={}
    
    for line in balfilename:
        value, name = line.split()
        if name[3] == ' ':
            customer_dict[name[1:]] = value
    balfilename.close()
    
    return customer_dict

Print the contents so you aren't flying blind.

def customer_dictionary():
    balfilename= open('balance.dat', 'r')
    customer_dict={}
     
    for line in balfilename:
        print "line =", line
        print "split =", line.split()
        value, name = line.split()
        if name[3] == ' ':
            customer_dict[name[1:]] = value
        else:
            print "name[3] =", name[3]
    balfilename.close()
     
    return customer_dict

Print the contents so you aren't flying blind.

def customer_dictionary():
    balfilename= open('balance.dat', 'r')
    customer_dict={}
     
    for line in balfilename:
        print "line =", line
        print "split =", line.split()
        value, name = line.split()
        if name[3] == ' ':
            customer_dict[name[1:]] = value
        else:
            print "name[3] =", name[3]
    balfilename.close()
     
    return customer_dict

Why is it telling me that customer_dict isn't defined??

Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
customer_dict
NameError: name 'customer_dict' is not defined

When i take out the paramter and test the function in shell(customer_dictionary()), it's returning an empty dictionary

What does this mean??

<_io.TextIOWrapper name='balance.txt' mode='r' encoding='US-ASCII'>
<_io.TextIOWrapper name='balance.txt' mode='r' encoding='US-ASCII'>
<_io.TextIOWrapper name='balance.txt' mode='r' encoding='US-ASCII'>
<_io.TextIOWrapper name='balance.txt' mode='r' encoding='US-ASCII'>

What does this mean??

*Edit*...^^^ Figured it out

New problem...

error:

Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    customer_dictionary()
  File "/Users/me/Desktop/Computer Science/problem1.2.py", line 7, in customer_dictionary
    key, value = line.split(',')
ValueError: need more than 1 value to unpack
def customer_dictionary():
    balfilename= open('balance.txt', 'r')
    lines=balfilename.readlines()
    print (lines)
    customer_dict={}
    for line in lines:
        key, value = line.split(',')
        if customer_dict.get(key):
            customer_dict[key] += int(value)
        else:
            customer_dict[key] = int(value)
        
    balfilename.close()
    
    return customer_dict
def customer_dictionary():
    balfilename= open('balance.txt', 'r')
    lines=balfilename.read()
    print (lines)
    customer_dict= {}
    for line in lines:
        customer_dict[lines.split(" ")[0]] =1
   
    balfilename.close()
   
   
   
    return customer_dict
115     139-28-4313     1056.30
135     706-02-6945      -99.06
143   595-74-5767     4289.07
155     972-87-1379     3300.26
{'115': 1}

why is the dictionary cutting off at the 1, instead of going all the way through?

Because you split first word from the text as many times as characters (which you you call line) in file. Add print(line, lines.split(' ', 1)[0]) inside the for loop to see.

Because you split first word from the text as many times as characters (which you you call line) in file. Add print(line, lines.split(' ', 1)[0]) inside the for loop to see.

Ok i think i have it figured out.. One problem though, my first key in the dictionary repeats itself. What's causing it? And will the /n at the end of each line make a difference when trying to modify the dictionary in my next step??

def customer_dictionary():
    balfilename= open('balance.txt', 'r')
    lines=balfilename.read()
    print (lines)
    customer_dict= {}
    for line in lines:
        customer_dict[lines.split(" ")[0]] =lines
    balfilename.close()
   
  return customer_dict
115     139-28-4313     1056.30
    135     706-02-6945      -99.06
    143   595-74-5767     4289.07
    155     972-87-1379     3300.26


    {'115': '115     139-28-4313     1056.30\n135     706-02-6945      -99.06\n143   595-74-5767     4289.07\n155     972-87-1379     3300.26\n}

You did not get it.

You did not get it.

You're right..

I'm completely stumped! You said to "Add print(line, lines.split(' ', 1)[0]) inside the for loop." I did that and i'm still getting errors.

Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    customer_dictionary()
  File "/Volumes/me/problem1.2.py", line 9, in customer_dictionary
    print(line,lines.split('',1)[0])
ValueError: empty separator
def customer_dictionary():
    balfilename= open('balance.txt', 'r')
    lines = balfilename.read()
    print (lines)

    customer_dict= {}
    for line in lines:
        customer_dict[lines.split(" ")[0]]= lines
    print(line,lines.split('',1)[0])
    balfilename.close()
    
    return customer_dict

You forgot space inside quotes. This is temporary debug print for you to understand your mistake.

:confused: :confused: It's a loop that goes on forever until it finally prints out

{'115': '115     139-28-4313     1056.30\n135     706-02-6945      -99.06\n143   595-74-5767     4289.07\n155     972-87-1379     3300.26\n162    814-50-7178     3571.94\n

.....


I understand that i'm new to this, but how hard is what i'm trying to do really?? considering how short the function is, it cannot be as hard as i'm making it out to me

I could make it one or two lines of pyTonyc code, but it is immaterial. You must do it your way and later adapt to pythonic ways. No use to give out code to you, now matter how trivial, as you would not learn anything.

Study strip and split method, float() function, open method and with statement for file management. http://docs.python.org/release/3.2/tutorial/inputoutput.html#reading-and-writing-files

I could make it one or two lines of pyTonyc code, but it is immaterial. You must do it your way and later adapt to pythonic ways. No use to give out code to you, now matter how trivial, as you would not learn anything.

Study strip and split method, float() function, open method and with statement for file management. http://docs.python.org/release/3.2/tutorial/inputoutput.html#reading-and-writing-files

NOt even tell me if i'm headed in the right direction??

I think you misunderstood what he was saying. We could TELL you that you're starting to think correctly, but there's still a big, essential piece missing from the puzzle for you. Pytony pointed you in the right direction though, you're getting closer. Check out what he showed you. and also try seeing exactly what's going on here:

{'115': '115 139-28-4313 1056.30\n135 706-02-6945 -99.06\n143 595-74-5767 4289.07\n155 972-87-1379 3300.26\n162 814-50-7178 3571.94\n}

Look closely at that format, I see a definite pattern. Once you read those this may become clearer, also think about how this format happened as a result of what is being iterated through, and how it's being iterated.

d ={}
balfilename = open('balance.txt', 'r')
lines= balfilename.readlines()

for line in lines:
    if line:
        line= ' '.join(lines)
        line= line.rstrip()
        line_content= line.split(' ')
        d[line_content[0]] = (line_content[1], line_content[2])
print(d)
balfilename.close()

Gives me an output of: {'115': ('', '')} Why does it not go all the way through?

print line before joining, print line after stripping, then print line after splitting. It's annoying but it'll help you see what's happening.

print line before joining, print line after stripping, then print line after splitting. It's annoying but it'll help you see what's happening.

What i got from it is that when storing my line_content, line_content[0] repeats itself over and over again, but line_content[1] and line_content[2] gets no data at all..:confused:

You must learn to debug by print, print and print:

from __future__ import print_function
d ={}
balfilename = open('balance.txt', 'r')
lines= balfilename.readlines()

for line in lines:
    if line:
        print(line)
        line= ' '.join(lines)
        print(line)
        line= line.rstrip()
        print(line)
        line_content= line.split(' ')
        print('Line content[0]:',line_content[0])
        d[line_content[0]] = (line_content[1], line_content[2])
print(d)
balfilename.close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.