Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.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_Path_Concatenation - Fatal编程技术网

Python 使用路径对文件进行读/写操作

Python 使用路径对文件进行读/写操作,python,path,concatenation,Python,Path,Concatenation,如何读取或写入与文件本身不在同一文件夹中的文件 我正在尝试编写一个函数,允许用户输入通过使用路径本身查找文件。我必须将其设置为用户输入文件名,然后输入路径 然后,我必须将它们连接在一起,形成完整的路径来定位文件。用于从不同的部分构造文件路径: import os.path dirname = '/foo/bar/baz' filename = 'ham_n_spam' path = os.path.join(dirname, filename) 我该如何做才能让用户自己放置路径?它是:dir

如何读取或写入与文件本身不在同一文件夹中的文件

我正在尝试编写一个函数,允许用户输入通过使用路径本身查找文件。我必须将其设置为用户输入文件名,然后输入路径

然后,我必须将它们连接在一起,形成完整的路径来定位文件。

用于从不同的部分构造文件路径:

import os.path

dirname = '/foo/bar/baz'
filename = 'ham_n_spam'
path = os.path.join(dirname, filename)

我该如何做才能让用户自己放置路径?它是:dirname=input()filename=input()path=os.path.join(dirname,filename)?@JustinFarr:你为什么不试试呢?你那样做会怎么样?我试过了,但我不知道怎么称呼它。import os.path dirname=input()filename=input()path=os.path.join(dirname,filename)read=open(path,“r”)def read_file():path=input(“输入包含文件的路径:”)file1=input(“输入要打开的文件名:”),open(file1,“r”)为x:return x.readlines()所以它告诉我目录或文件不存在。我只是想弄清楚如何用我的函数实现它。我很抱歉把这一切搞得一团糟is@JustinFarr:因此
file1
不是有效路径。试着想想我告诉你的,以及这如何应用于
read_file()
函数中的
file1
path
变量。因此,我必须将“file1”更改为“filename”变量,这样它才是有效的路径?