2014-02-10 36 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) –

相关问题