简体   繁体   中英

Python - Store strings from text file into a variable

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.

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM