2014-02-10 38 views
0

如何讀取文件輸入,然後說出是否不是一年,那麼不要使用該數據。如果是一年(4位數字),那麼通過簡單的數學計算是否是閏年。Python:如何從文件中讀取數據並與其進行數學運算

我在問更多,所以如何用文件來做到這一點。我可以正常地進行數學運算,但是當文件涉及到時,我不知道文件是如何工作的。

編輯 此外,我如何做單獨的函數來檢查輸入是否是數字,以及另一個函數來計算它是否是閏年。

file_name_one =輸入( 「第一文件名:」) file_stream =開放(file_name_one, 「R」)

用於線在file_stream: year_str =行[:4] 年= 0 leap_year = 0 div_4 = 0 div_100 = 0 div_400 = 0

if year_str.isdigit(): # test if year_str is an integer 
    year = int(year_str) 
    if year%4 == 0:   # check if the year is a leap year 
     div_4 = 1 
    if year%100 == 0: 
     div_100 = 1 
    if year%400 == 0: 
     div_400 = 1 
    if div_4 == 1 & div_100 == 0: 
     print (line[:4], "is a leap year") 
    if div_4 == 1 & div_100 == 0 & div_400 == 1: 
     print (line[:4], "is a leap year") 
    div_4 = 0 
    div_100 = 0 
    div_400 = 0 
+3

*我不知道文件是如何工作的*那麼你肯定會想採取偷看在[文件](http://docs.python.org /2/tutorial/inputoutput.html) –

+0

我有這本書,我一直在閱讀,但我不知道它是如何工作的。 – user3294540

+0

下面的答案顯示了文件的工作方式。把文件對象當作一個字符串對象,一次一行地流入python。你用這個字符串對象做什麼取決於你。你真的想要做什麼與輸出和文件是什麼樣子 - 這將幫助我們更好地回答你的問題。否則,下面的答案足以解決上述問題。 – gabe

回答

1

,如果我知道你想從文件中讀取,是嗎?

意願的是,它真的很容易:

with open("filename","r") as file : 
    input = file.read() 
1

如果文件被命名爲「foo.txt的」,如果你是在文件的同一目錄下,則是這樣的:

file_stream = open("foo.txt",'r') 
for line in file_stream: 

    # as suggested in the comment, it might be a good idea to print the line, 
    # just so you know what the file looks like 
    print line 

    # the variable line is a string. depending on the formatting of the file, 
    # something along these lines might work: 

    year_str = line[:4] 
    if year_str.isdigit(): # test if year_str is an integer 
     year = int(year_str) 
     if not year%4:   # check if the year is a leap year 
      # 
      print "%s is a leap year %s"%year 
      .... 
+0

顯示用戶讀取的文件的內容不是很好嗎?所以如果他想運行你的代碼,他可以有一個完整的例子?也許有些人讚揚發生了什麼。 –

+0

取決於你的需求。也許。也許不是?值得注意的是(我會在上面)這個問題並沒有說明實際上想要處理的數據或者文件的外觀,有多大,等等。這是它的工作原理的一般框架 - 但更精細分數取決於意圖和數據。 – gabe

+1

同意。我正在閱讀答案,並且因爲問題被接受,所以似乎是最適合投票的。我想提到它可以幫助OP多一點。 –

0

如果你需要讀取多行數據,readlines()是一個很好的函數。試試這個:

f = open("myfile.txt", "r") 
lines = f.readlines() 
for line in lines: 
    print line 

修改第四行來檢查你的數據是否看起來像一年。

+0

請注意,這會將整個文件加載到內存中。關於文件對象的好處在於它們本身是可迭代的 - 因此您可以將對象視爲流。 – gabe

0

爲您更新的問題:

import re 

def check_is_year(year): 
    # implement as per other answers 
    return True # if `year` is valid, else return False 

def check_is_leap(year): 
    # implement as you will 
    return True # if `year` is a leap year, else False 

with open("foo.txt") as f: 
    years = [year for year in re.findall("/b/d{4}/b",f.read()) if check_is_year(year)] 
    for year in years: 
     if check_is_leap(year): 
      # do whatever you want. 
+0

什麼是進口? – user3294540

+0

@ user3294540're'是在Python中處理正則表達式的模塊。後來我使用了''''''''''''''''''後來我使用了''/ b/d {4}/b'('/ b')的're.findall(「/ b/d {4}/b」,f.read是一個單詞的邊界,例如空格或製表符等,'/ d'是一個數字1234567890,'{4}'表示它必須匹配前面語句的4) –

相關問題