从文本文件中读取不同类型的文件-Python [已关闭] 。

问题描述 投票:-2回答:1

我有一个文本文件 "input.txt"。它看起来像这样。

3


a b c
d e f 
g h i

我想写一个python程序,将3读为整数,其余的读为列表。我怎样才能实现这个目标?有什么建议吗?

先谢谢你。

python python-3.x list int text-files
1个回答
1
投票

这里有一个示例解决方案。

#!/usr/bin/python3

filename = "input.txt"

with open(filename) as inputFile:
    firstLine = inputFile.readline()
    firstLine = firstLine.strip()
    if not firstLine.isdigit():
        raise TypeError("File content is invalid")

    myInt = int(firstLine)

    myListsVersion1 = list()
    myListsVersion2 = list()
    myListsVersion3 = list()
    for line in inputFile.readlines():
        line = line.strip()
        if len(line) == 0: # or # if not line
            continue

        myListsVersion1.append(line)

        currentLineAsList = line.split()
        myListsVersion2.append(currentLineAsList)
        myListsVersion3.extend(currentLineAsList)

    print(myInt)
    print(myListsVersion1)
    print(myListsVersion2)
    print(myListsVersion3)

根据你的输入,这将是结果。

$ python3 script.py 
3
['a b c', 'd e f', 'g h i']
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

建议:

我想你是第一次接触python吧?那么你可以参考下面这个小抄。我保证通过这个小抄,你会学到很多东西,尤其是第1到14页。

对于字符串操作来说,这是非常有用的。

© www.soinside.com 2019 - 2024. All rights reserved.