0

I'm wanting a script that will store the first word from each line from an input file into a variable.

Current code only stores the last name.

def func(file): 
  global user 
  with open(file) as iFile: 
    for line in iFile: 
    string = line.split(',') 
    user = string[0]

func(sys.argv[1]) 
print user

The text file input is:

string1,string2,string3
string1,string2,string3
string1,string2,string3

I want the variable user to store the all of the string1's on each line from the text file.

3
  • Your indentation is incorrect, you may want to correct that. Next, you are confusing user and username in your code. Last but not least, did you want a list of strings perhaps? Commented Jul 8, 2014 at 10:10
  • Sorry, corrected the 'user' and 'username'. Yes, a list would work. Not too sure though, hehe. New to this. Commented Jul 8, 2014 at 10:13
  • make user a list user.append( string[0]) Commented Jul 8, 2014 at 10:14

3 Answers 3

1

Indenting issue.

This will fix it. I also changed your func, so that you no longer use a global but instead return a generator with the users from the list.

This is a better practise and more memory efficient.

def func(file): 
  with open(file) as iFile: 
    for line in iFile: 
        string = line.split(',') 
        yield string[0]

for user in func(sys.argv[1]) 
    print user
Sign up to request clarification or add additional context in comments.

Comments

1

i recommend this

def func(path):
    with open(path) as _file:
        return [s.split(',')[0] for s in _file]

user = func(sys.argv[1])
print user

Comments

0

I would go for this :

user = []
def func(file): 
  with open(file) as iFile: 
    for line in iFile: 
      user.append(line.split(',')[0])

func(sys.argv[1]) 
print user

It stores in a list all "first string" of every line you will provide to the function. By the way the solution of Matt PsyK is totally more efficient!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.