如何使用Python代码打印文件的前几行或末尾几行?
- 内容介绍
- 文章标签
- 相关推荐
本文共计387个文字,预计阅读时间需要2分钟。
pythonimport sys
def main(): if len(sys.argv) <2: print(Usage: python head.py [lines]) return
file_path=sys.argv[1] lines=int(sys.argv[2]) if len(sys.argv) > 2 else 10
try: with open(file_path, 'r') as file: for i, line in enumerate(file): if i >=lines: break print(line, end='') except FileNotFoundError: print(fFile {file_path} not found.) except Exception as e: print(fAn error occurred: {e})
if __name__==__main__: main()
写一个类似linux head的小工具,在window下用。
本文共计387个文字,预计阅读时间需要2分钟。
pythonimport sys
def main(): if len(sys.argv) <2: print(Usage: python head.py [lines]) return
file_path=sys.argv[1] lines=int(sys.argv[2]) if len(sys.argv) > 2 else 10
try: with open(file_path, 'r') as file: for i, line in enumerate(file): if i >=lines: break print(line, end='') except FileNotFoundError: print(fFile {file_path} not found.) except Exception as e: print(fAn error occurred: {e})
if __name__==__main__: main()
写一个类似linux head的小工具,在window下用。

