使用.py scrip运行.txt文件

2024-09-29 17:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法在文件上读取和执行cat(文件名)函数小.txt在我的windows终端。python脚本名为你好,派瑞. 跑步你好,派瑞小.txt没有显示结果。脚本代码如下:

    import sys
    def cat(filename):
        f=open (filename,'rU')
        text = f.read()
        print text
    def main():
        cat (sys.agrv[1])
    # This is the standard boilerplate that calls the main() function.
    if __name__ == '__main__':
        main()

   RESTART: C:\Users\WELCOME\google-python-exercises\hello.py

   Traceback (most recent call last):
   File "C:\Users\WELCOME\google-python-exercises\hello.py", line 34, in <module>
   main()
   File "C:\Users\WELCOME\google-python-exercises\hello.py", line 30, in main
   cat (sys.agrv[1])
   AttributeError: 'module' object has no attribute 'agrv'

Tags: textpytxt脚本hellomaindefgoogle
1条回答
网友
1楼 · 发布于 2024-09-29 17:20:37

有一个拼写错误agrv。读取文件后,不能关闭它。试试这个:

import sys

def cat(filename):    
    f = open(filename)
    text = f.read()
    f.close()
    print(text)

def main():
    cat(sys.argv[1])

if __name__ == '__main__':
    main()

我将使用with语句重写cat()函数,因为它负责关闭文件。你知道吗

def cat(filename):    
    with open(filename) as f:
        text = f.read()
    print(text)

Python Tutorial说:

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.

相关问题 更多 >

    热门问题