簡體   English   中英

Python,一一讀取文件中的行

[英]Python, reading lines from a file one by one

即時通訊程序會找出有效和無效的社會安全號碼。

該程序應該能夠對我計算機上文本文件中的數字進行排序。 但是即時通訊只能一次輸入所有數字(我認為)。 我不會程序一一檢查數字。

這就是現在的樣子

def fileinput():
    try:
        textfile = open("numberlist.txt","r")
        socialsecuritynumber = textfile.read()
        numberprogram(socialsecuritynumber)
    except IOError:
        print("there's no such file!\n")

有人知道我應該怎么做嗎? 文本文件只包含數字

  • 1993-06-11 5570
  • 930611-5570
  • 930611 5570
  • 93 05115570
  • 1993 05 11 55 70
  • 1993 05 11 5570

這是我文本文件中的數字

  1. 始終使用with語句讀取文件。 因此,如果在讀取過程中出現問題,或者代碼塊中存在異常,則文件將自動關閉。
  2. 然后使用for循環像這樣逐行讀取

     with open("numberlist.txt","r") as textfile: for line in textfile: print line 

如您所建議的那樣使用。 您可以使用readLines()方法,並使用for-in循環逐行遍歷行,並檢查其有效性。 這將確保即使對於大文件,您的代碼也不會中斷。

with open("numberlist.txt") as f: # this auto closes the file after reading. It's good practice
    numbers = f.readlines() # numbers is a list of all the numbers(a list of lines in the file)

如果行中有多余的空格(或者以防萬一):

numbers = [n.strip() for n in numbers] # takes out unwanted spaces on the ends

如果您發現數字后面有逗號或其他內容,則可以執行以下操作:

numbers = [n[:-1] for n in numbers] # slices off the last character of each line/list item

for number in numbers:
    #do whatever you want here

編輯:

另外,您可以使用正則表達式,而逗號和空格無關緊要:

import re

n = ['1993-06-11 5570',
     '930611-5570',
     '930611 5570',
     '93 05115570',
     '1993 05 11 55 70',
     '1993 05 11 5570']

regex = '([0-9]+(?:[- ]?[0-9]+)*)'
match_nums = [re.search(regex, num) for num in n]
results = [i.groups() for i in match_nums]
for i in results:
    print i

('1993-06-11 5570',)
('930611-5570',)
('930611 5570',)
('93 05115570',)
('1993 05 11 55 70',)
('1993 05 11 5570',)

有關正則表達式的信息,請參見此處

建議使用with進行文件操作。 如果是Python 2.4之類的東西,則必須使用with語句導入。 我想到的最簡單的數字問題解決方案是:

from __future__ import with_statement
file_with_ssn = "/absolute/path/to/the/file"

try:
    with open(file_with_ssn) as ssn_file:
        for ssn in ssn_file:
            ssn = filter(str.isdigit, ssn)
            # This removes anything other than a number including -.
            # Since SSN cannot be in negative, isdigit is fine here
            numberprogram(ssn)
except EnvironmentError:
    print "IOError or OSError or WindowsError happened"

暫無
暫無

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

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