Python 从dfferent函数返回文本文件后,无法读取该文件
我有一个代码,我正在向一个文件写入一些行,然后尝试在一个单独的函数中读取该文件Python 从dfferent函数返回文本文件后,无法读取该文件,python,file,Python,File,我有一个代码,我正在向一个文件写入一些行,然后尝试在一个单独的函数中读取该文件 def start(): task_file, task_dir, command_file=parse_json_and_create_folders() for i in range(len(task_file)): with open('sscd_file', 'a') as mfile: dir_name = "TASKFOLDER"
def start():
task_file, task_dir, command_file=parse_json_and_create_folders()
for i in range(len(task_file)):
with open('sscd_file', 'a') as mfile:
dir_name = "TASKFOLDER" + str(i)
file_path= task_dir + "/" + dir_name
os.chdir(file_path)
inp_file=command_file.rsplit('/', 1)[-1]
wor_folder=command_file.rsplit('/', 1)[-2]
inp_file_path=os.path.join(file_path, wor_folder)
line = "-E " + "cd" + file_path + " -o " + file_path + "-%T.out" + application_name + " inp=" + inp_file
mfile.write(line)
return mfile.name
def read_task_file():
myfile=start()
with open(myfile, 'r') as f:
print(f.readlines())
读取任务文件()
当我试图在read()中读取此文件时,错误显示为
with open(myfile, 'r') as f:
IOError: [Errno 2] No such file or directory: 'sscd_file'
我不确定这里出了什么问题。
有人能帮我一下吗您用
os.chdir(file\u path)
更改了目录,但没有返回原始目录。现在Python将在新的当前目录中搜索该文件,file\u path
如上所述,open
使用“绝对或相对于当前工作目录”的路径。像“theu file”
这样的路径是相对路径,因此open
确实会在新的当前目录中搜索该文件
下面是一个例子:
>>> os.listdir() # the contents of the current directory
['.DS_Store', 'fof.pyc', 'test_venv', 'fof.py', '__pycache__', 'test.py', 'compile_ios', 'venv', 'v']
>>> with open('hello.txt', 'w') as f: # open a file in THIS directory
... os.chdir('venv') # change to another directory
... f.write('hello!')
...
6
>>> os.getcwd() # I remain in this new directory
'/Users/forcebru/test/venv'
>>> os.listdir() # there's no 'hello.txt'
['bin', 'include', 'pyvenv.cfg', 'lib']
>>> os.chdir('..') # go back
>>> os.getcwd()
'/Users/forcebru/test'
>>> os.listdir() # 'hello.txt' is here, as expected
['.DS_Store', 'fof.pyc', 'test_venv', 'fof.py', '__pycache__', 'test.py', 'compile_ios', 'venv', 'hello.txt', 'v']
>>>
使用绝对路径打开(“/Users/forcebru/test/hello.txt”)将打开这个确切的文件,而不考虑当前工作目录。您是否也可以共享
解析json和创建文件夹()
?为什么在你的语句中间有一个<代码> OS.CHDIR()/<代码?是的,这是我的坏消息,我给出了完整的路径,它是有效的。但是,当我打开文件进行读取时,它会以列表格式提供数据,@prex,您使用的是什么命令,它的输出是什么<例如,code>read()将始终返回单个字符串,但readlines()
将返回字符串列表。