【发布时间】: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