【问题标题】:Open and print the contents of a file?打开并打印文件的内容?
【发布时间】:2021-03-01 08:16:38
【问题描述】:

我正在尝试编写一个可以打开文件并打印其内容的程序。我想我在定义它时遇到了一些麻烦?如果它没有告诉我“路径”未定义,那么它告诉我“new_dir”未定义。

代码如下:

import pathlib

def prog_info():
    print("This program will open a file, read and print its contents.")
    print("-----------------------------------------------------------")


prog_info()

file_path = new_dir / "numbers.txt"
file_path.parent.mkdir()
file_path.touch()

with path.open("numbers.txt", mode="r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())

文件将打印三个数字:

22
14
-99

【问题讨论】:

  • new_dir 变量目前未定义。您需要将其设置为您的文件夹路径(例如new_dir="C:\Program Files\Folder"
  • 请在您的帖子中包含错误堆栈跟踪

标签: python windows file directory path


【解决方案1】:
with open("filename or location", 'r') as my_file:
    for line in my_file:
        print(line)

我希望这对您有所帮助。 您不需要模式,也不需要导入。您只需要提供的代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多