简体   繁体   中英

Testing each line in a file

I am trying to write a Python program that reads each line from an infile. This infile is a list of dates. I want to test each line with a function isValid(), which returns true if the date is valid, and false if it is not. If the date is valid, it is written into an output file. If it is not, invalid is written into the output file. I have the function, and all I want to know is the best way to test each line with the function. I know this should be done with a loop, I'm just uncertain how to set up the loop to test each line in the file one-by-one.

Edit: I now have a program that basically works. However, I am getting incorrect output to the output file. Perhaps someone will be able to explain why.

Ok, I now have a program that basically works, but I'm getting strange results in the output file. Hopefully those with Python 3 experience can help.

   def main():
datefile = input("Enter filename: ")
t = open(datefile, "r")
c = t.readlines()
ofile = input("Enter filename: ")
o = open(ofile, "w")



for line in c:
    b = line.split("/")
    e = b[0]
    f = b[1]
    g = b[2]

    text = str(e) + " " + str(f) + ", " + str(g)
    text2 = "The date " + text + " is invalid"

    if isValid(e,f,g) == True:
        o.write(text)

    else:
        o.write(text2)



def isValid(m, d, y):
if m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m == 10 or m == 12:
    if d is range(1, 31):
        return True
elif m == 2:
    if d is range(1,28):
        return True
elif m == 4 or m == 6 or m == 9 or m == 11:
    if d is range(1,30):
        return True
else:
    return False

This is the output I'm getting.

The date 5 19, 1998 is invalidThe date 7 21, 1984 is invalidThe date 12 7, 1862 is invalidThe date 13 4, 2000 is invalidThe date 11 40, 1460 is invalidThe date 5 7, 1970 is invalidThe date 8 31, 2001 is invalidThe date 6 26, 1800 is invalidThe date 3 32, 400 is invalidThe date 1 1, 1111 is invalid

In the most recent versions of Python you can use the context management features that are implicit for files:

results = list()
with open(some_file) as f:
    for line in f:
        if isValid(line, date):
            results.append(line)

... or even more tersely with a list comprehension:

with open(some_file) as f:
    results = [line for line in f if isValid(line, date)]

For progressively older versions of Python you might need to explicitly open and close the file (with simple implicit iteration over the file for line in file: ) or add more explicit iteration over the file ( f.readline() or f.readlines() (plural) depending on whether you want to "slurp" in the entire file (with the memory overhead implications of that) or iterate line-by-line).

Also note that you may wish to strip the trailing newlines off these file contents (perhaps by calling line.rstrip('\\n') --- or possibly just line.strip() if you want to eliminate all leading and trailing whitespace from each line).

(Edit based on additional comment to previous answer):

The function signature isValid(m,d,y) suggests that you're passing a data to this function (month, day, year) but that doesn't make sense given that you must also, somehow, pass in the data to be validated (a line of text, a string, etc).

To help you further you'll have to provide more information (preferable the source or a relevant portion of the source to this "isValid()" function.

In my initial answer I was assuming that your "isValid()" function was merely scanning for any valid date in its single argument. I've modified my code examples to show how one might pass a specific date, as a single argument, to a function which used this calling signature: "isValid(somedata, some_date)."

with open(fname) as f:
    for line in f.readlines():
        test(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM