简体   繁体   English

Python-将字符串从文本文件存储到变量中

[英]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. 我希望变量user在文本文件的每一行上存储所有string1。

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. 我还更改了func,以便您不再使用全局函数,而是从列表中返回带有用户的生成器。

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! 顺便说一句,Matt PsyK的解决方案效率更高!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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