如何让Python读取新行和行?

时间:2015-05-22 19:27:53

标签: python

我知道Python可以读取如下数字:

8
5
4
2
2
6

但我不知道如何让它读起来像:

8 5 4 2 2 6

另外,有没有办法让python双向阅读?例如:

8 5 4
2
6

我认为用新行阅读将是:

info = open("info.txt", "r")
lines = info.readlines()
info.close()

如何更改代码,以便它可以向下读取,如上面的第三个示例中那样?

我有一个这样的程序:

info = open("1.txt", "r")
lines = info.readlines()

numbers = []
for l in lines:
    num = int(l)
    numbers.append(str(num**2))
info.close()

info = open("1.txt", "w")
for num in numbers:
    info.write(num + "\n")
info.close()

如何让程序分别在新行和行中读取每个数字?

7 个答案:

答案 0 :(得分:1)

将它们保存为字符串:

with open("info.txt") as fobj:
    numbers = fobj.read().split()

或者,将它们转换为整数:

with open("info.txt") as fobj:
    numbers = [int(entry) for entry in fobj.read().split()]

每行使用一个数字和几个数字。 这个文件内容:

1
2
3 4 5
6
7
8 9 10
11

将导致numbers的输出结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

此方法立即读取整个文件。除非您的文件非常大,否则这很好。

答案 1 :(得分:0)

info = open("1.txt", "r")
lines = info.readlines()

numbers = []
for line in lines:
    for num_str in line.split(' '):
        num = int(num_str)
        numbers.append(str(num**2))
info.close()

答案 2 :(得分:0)

info = open("test.txt", "r")
lines = info.readlines()
numbers = []
for l in lines:
    l = l.strip()
    lSplit = l.split(' ')
    if len(lSplit) == 1:
        num = int(l)
        numbers.append(str(num**2))
    else:
        for num in lSplit:
            num2 = int(num)
            numbers.append(str(num2**2))
print numbers
info.close()

答案 3 :(得分:0)

file_ = """
1 2 3 4 5 6 7 8 
9 10 
11
12 13 14
"""


for number in file_ .split():
    print number

>>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

答案 4 :(得分:0)

执行此操作的一种好方法是使用生成器迭代线,并且对于每一行,生成其上的每个数字。如果线上只有一个数字(或没有),这样可以正常工作。

def numberfile(filename):
    with open(filename) as input:
         for line in input:
             for number in line.split():
                 yield int(number)

然后你可以写,例如:

for n in numberfile("info.txt"):
    print(n)

答案 5 :(得分:0)

如果你不关心每行有多少个数字,那么你可以尝试这个来创建所有数字的正方形列表。

我通过简单地使用- (void)rightBarButtonPress { //toggle selected state of button UIBarButtonItem *rightBarButton = self.navigationItem.rightBarButtonItem; UIButton *button = (UIButton *)rightBarButton.customView; [button setSelected:!button.selected]; //do whatever else you gotta do } 语句迭代打开的文件来简化您的代码,但迭代with结果也同样适用(对于小文件 - 对于大文件,此方法并不要求您将文件的全部内容保存在内存中。

readlines()

答案 6 :(得分:0)

另一种尚未张贴的方式...

numbers = []
with open('info.txt') as f:
    for line in f:
        numbers.extend(map(int, line.split()))