Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打开并打印文件的内容?_Python_Windows_File_Directory_Path - Fatal编程技术网

Python 打开并打印文件的内容?

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("--------------------------------

我试图写一个程序,将打开一个文件,并打印其内容。我想我在定义它时遇到了一些麻烦?如果它没有告诉我“路径”没有定义,那么它就是在告诉我“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\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)