繁体   English   中英

如何从python中的文本文件打印特定行

[英]How to print specific lines from a text file in python

我已经编写了可以让我在行中输入数字的代码,但是现在,在我得到的所有数字中,我必须制作 comp。 打印可以很好地被 2 整除的那些到目前为止这是我得到的:

i = 0
x = 1
y = 0
z = 20
My_file = open("Numbers", 'w')
while i < z:
    My_file.write(str(x))
    My_file.write("\n")
    x = x + 1
    i = i + 1
My_file.close()
i = 0
My_file = open("Numbers", 'r')
for line in My_file:
    if int(My_file.readline(y)) % 2 == 0:
        print(My_file.readline(y))
    y = y + 1

最重要的是,我的问题是int(My_file.readline(y)) % 2 == 0是废话,它说:

invalid literal for int() with base 10: ''.

每行包含一个换行符( "2\\n" ),您需要在转换为数字之前删除\\n

...
My_file = open("Numbers", 'r')
for line in My_file:
    line = line.strip() # removes all surrounding whitespaces!
    if int(line) % 2 == 0:
        print(line)
    y = y + 1

出去:

2
4
6
8
10
12
14
16
18
20

根据之前的答案,这是一个完整的示例:

start_value = 1
max_value = 12
filename = "numbers"

with open(filename, "w") as my_file:
    value = start_value
    while value <= max_value:
        my_file.write(f"{value}\n")
        value += 1

with open(filename, "r") as my_file:
    lines = my_file.readlines()

for line in lines:
    line = line.strip()
    if int(line) % 2 == 0:
        print(line)

这段代码利用了python的“上下文管理器”( with关键字)。 open() ,它可以很好地处理文件的关闭。

您的错误来自每个数字末尾的\\n strint的转换不起作用,因为解释器无法找到如何转换这个字符。

作为一个好习惯,使用有意义的变量名称,当你在这里提问时更是如此:它可以帮助人们更快地理解代码。

这是否有帮助:

MAXINT = 20
FILENAME = 'numbers.txt'

with open(FILENAME, 'w') as outfile:
    for i in range(1, MAXINT+1):
        outfile.write(f'{i}\n')
with open(FILENAME) as infile:
    for line in infile:
        if int(line) % 2 == 0:
            print(line, end='')

这有效:

FILE_NAME = 'Numbers.txt'
MAX_NUMBER = 20

with open(FILE_NAME, 'w') as file:
    numbers = list(map(str, range(MAX_NUMBER)))
    for n in numbers:
        file.write(n)
        file.write('\r')
with open(FILE_NAME, 'r') as file:
    for number in file:
        if int(number) % 2 == 0:
            print(number, end='')

输出:


0
2
4
6
8
10
12
14
16
18

暂无
暂无

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

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