簡體   English   中英

如何讀取文件並僅用特定位數打印行

[英]How to read a file and print lines with only a certain amount of digits

input_file = input("Open what file:")

try:
    input_file = open(input_file)
    for line_str in input_file:
         if input_file == 4 and line_str.isdigit():
    print(line_str)

except IOError:
    print("The input file doesn't exist.")
    sys.exit(1)

    input_file.close

在我的文本文件中,我有以下數字:

174862
2000
2400
9996
12
55

我該如何做才能只打印至少4位的數字?

您需要刪除添加到line_str的新行char。

嘗試這樣的事情:

input_file = "file.txt"

try:
    input_file = open(input_file)
    for line_str in input_file:
        line_str = line_str.strip()

        if len(line_str) == 4 and line_str.isdigit():
            print(line_str)

except IOError:
    print("The input file doesn't exist.")
    sys.exit(1)

    input_file.close

您還可以使用正則表達式查看是否有一組4位數字。 如果您需要我可以補充說明。

編輯:要使用正則表達式進行匹配,可以使用以下內容

import re
line_str = line_str.strip()

    if re.match(r'^[0-9]{4}$', line_str):
            print "RE " + line_str

re是pythons正則表達式模塊。 如果沒有匹配項,則re.match將返回None對象。 因此,您可以在if條件中直接使用它。 r'^ [0-9] {4} $'-基本上是您的正則表達式。 “ ^”表示開始,“ $”表示結束。 [0-9]是數字范圍,{}表示計數。

希望它能清除一切。

而不是比較input_file == 4 (永遠不會為真,因為input_file是文件對象,而不是整數),而是想將line_strlen與4進行比較。請嘗試:

for line_str in input_file:
    if len(line_str) >= 4 and line_str.isdigit():
        print(line_str)

這將僅打印至少四個字符長且僅由數字組成的行。

您可能還應該使用with語句來處理文件的關閉,但這是一個小問題(如果沒有它,它可能會起作用)。

import re
try:
    input_file = open("input.txt",'r')
    x=input_file.read()
    print re.findall(r"(\d{4,})",x)


except IOError:
    print("The input file doesn't exist.")
    sys.exit(1)

    input_file.close

試試這個。這將給出大於長度4的所有數字。

這也不會遍歷文件。

您可以使用len()函數檢查正在讀取的數字的長度。

我已經修改了您的程序。

import sys
input_file = input("Open what file:")

try:
    with open(input_file) as in_file:
        for line_str in in_file:
         if len(line_str.strip()) >= 4 and line_str.strip().isdigit():

            print(line_str.strip())

except IOError:
    print("The input file doesn't exist.")
    sys.exit(1)

另外,當您with使用時,您不需要關閉文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM