Python 打开并打印文件的内容?
我试图写一个程序,将打开一个文件,并打印其内容。我想我在定义它时遇到了一些麻烦?如果它没有告诉我“路径”没有定义,那么它就是在告诉我“new_dir”没有定义 代码如下:Python 打开并打印文件的内容?,python,windows,file,directory,path,Python,Windows,File,Directory,Path,我试图写一个程序,将打开一个文件,并打印其内容。我想我在定义它时遇到了一些麻烦?如果它没有告诉我“路径”没有定义,那么它就是在告诉我“new_dir”没有定义 代码如下: import pathlib def prog_info(): print("This program will open a file, read and print its contents.") print("--------------------------------
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\u dir
变量目前尚未定义。您需要将其设置为文件夹路径(例如new\u dir=“C:\Program Files\folder”
),请在帖子中包含错误堆栈跟踪
with open("filename or location", 'r') as my_file:
for line in my_file:
print(line)