[英]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
。 從str
到int
的轉換不起作用,因為解釋器無法找到如何轉換這個字符。
作為一個好習慣,使用有意義的變量名稱,當你在這里提問時更是如此:它可以幫助人們更快地理解代碼。
這是否有幫助:
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.