简体   繁体   English

CSV文件无法打印?

[英]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

You need to call the main function at the end of the program: 您需要在程序结束时调用main函数:

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). Python没有像C / C ++那样的main函数(在运行程序时会隐式调用它)。 Instead, Python treats the function you have defined as it would any other function. 相反,Python会将您定义的函数视为任何其他函数。 The name main is only significant to the humans reading your code (and maybe some code analysis tools). 名称main仅对人类阅读代码很重要(可能还有一些代码分析工具)。


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. 这可确保仅在直接运行程序时调用main函数。 If you import your file however, the call to main will be skipped. 但是,如果导入文件,则会跳过对main的调用。 For more information, see: 有关更多信息,请参阅:

What does if __name__ == "__main__": do? 如果__name__ ==“__ main__”:怎么办?

So to add to what iCodez said: 所以要添加到iCodez所说的内容:

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 会为你工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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