Yeej
Yeej

Reputation: 31

CSV file not printing?

Can anyone explain why this won't print anything?

import csv 

def main():
    with open('MaxWatt1.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            print row

Upvotes: 1

Views: 1789

Answers (2)

user2555451
user2555451

Reputation:

You need to call the main function at the end of the program:

import csv 

def main():
    with open('MaxWatt1.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            print row

main() # Call main function.

Python does not have a main function like C/C++ does (one which gets called implicitly when you run the program). Instead, Python treats the function you have defined as it would any other function. The name main is only significant to the humans reading your code (and maybe some code analysis tools).


Actually, it would probably be best to do:

import csv 

def main():
    with open('MaxWatt1.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            print row

if __name__ == '__main__':
    main()

This ensures that the main function is only called when you run the program directly. If you import your file however, the call to main will be skipped. For more information, see:

What does if __name__ == "__main__": do?

Upvotes: 3

notorious.no
notorious.no

Reputation: 5107

So to add to what iCodez said:

import csv 

def main():
    with open('MaxWatt1.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            print row

main()

will work for you

Upvotes: 0

Related Questions