【问题标题】:Import txt file and having each line as a list导入 txt 文件并将每一行作为列表
【发布时间】:2013-08-29 05:18:48
【问题描述】:

我是 Python 新用户。

我有一个 txt 文件,类似于:

3,1,3,2,3
3,2,2,3,2
2,1,3,3,2,2
1,2,2,3,3,1
3,2,1,2,2,3

但可能会更少或更多行。

我想将每一行作为列表导入。

我知道你可以这样做:

filename = 'MyFile.txt' 
fin=open(filename,'r')
L1list = fin.readline()
L2list = fin.readline()
L3list = fin.readline()

但由于我不知道我会有多少行,有没有另一种方法来创建单独的列表?

【问题讨论】:

    标签: python list python-3.x file-io


    【解决方案1】:

    不要创建单独的列表;创建列表列表:

    results = []
    with open('inputfile.txt') as inputfile:
        for line in inputfile:
            results.append(line.strip().split(','))
    

    或者更好的是,使用csv module:

    import csv
    
    results = []
    with open('inputfile.txt', newline='') as inputfile:
        for row in csv.reader(inputfile):
            results.append(row)
    

    列表或字典是高级结构,用于跟踪从文件中读取的任意数量的内容。

    请注意,任一循环还允许您单独寻址数据行,而无需将文件的所有内容读入内存;而不是使用results.append(),只需在此处处理该行即可。

    为了完整起见,这里是一次性将 CSV 文件读入列表的单行紧凑版本:

    import csv
    
    with open('inputfile.txt', newline='') as inputfile:
        results = list(csv.reader(inputfile))
    

    【讨论】:

      【解决方案2】:

      创建列表列表:

      with open("/path/to/file") as file:
          lines = []
          for line in file:
              # The rstrip method gets rid of the "\n" at the end of each line
              lines.append(line.rstrip().split(","))
      

      【讨论】:

      • 嗨 iCodez- 我实际上正在尝试使用它,虽然它正在制作列表列表,但列表中实际上只有一个项目 - 我现在正在使用的输入文件(如原始问题中所引用的)有三行,所以应该有三个列表。使用你的方法我只是得到 [['3', '2', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1\r1', '1', '1', '1', '3', '3', '1', '1', '2', '2', '1', '3']]。有什么想法吗?非常感谢。
      • @John - 我无法重现您的问题。我在您提供的 5 行示例中测试了我的代码,它的工作原理与应有的一样。它列出了 5 个列表,每行一个。您确定文件有 3 行而不是只有一长行吗?
      • @John - 另外,我会查看关于 Pieters 答案的评论,解释 open 内置。也许这可以解决你的问题。
      • 感谢 iCodez- 这确实是我的问题。我有两个版本的测试 .txt 文件一直在使用,并且一直指向错误的版本....感谢您的耐心和帮助!
      • @John - 非常乐意提供帮助!不过不要忘记接受答案(单击勾号),以帮助保持整洁有序(所有未接受答案的问题都保留在“未回答”垃圾箱中)。
      【解决方案3】:
      with open('path/to/file') as infile: # try open('...', 'rb') as well
          answer = [line.strip().split(',') for line in infile]
      

      如果您希望数字为ints:

      with open('path/to/file') as infile:
          answer = [[int(i) for i in line.strip().split(',')] for line in infile]
      

      【讨论】:

      • 谢谢!一个后续问题-0 我收到错误文件“seventeen_v2.3.py”,第 7 行,在 answer = [[int(i) for i in line.strip().split(',' )] for line infile] ValueError: invalid literal for int() with base 10: '1\r1' txt 文件中只有数字 - 知道为什么 python 将这个“\r1”添加到输入中吗?跨度>
      【解决方案4】:
      lines=[]
      with open('file') as file:
         lines.append(file.readline())
      

      【讨论】:

      • 您需要给出更完整的答案。就目前而言,这并不能满足 OP 的要求。
      猜你喜欢
      • 2018-04-10
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 2015-02-09
      相关资源
      最近更新 更多