我想将输出文件写入添加到path1的目录中。但是,当我尝试这样做时,会发生错误。
import os
import sys
path = 'ODOGS/LAB'
path1= 'ODOGS/lab_res_voiced'
for file in os.listdir(path):
current = os.path.join(path, file)
name_output=file #name of the current file must be the same for the output file
index_list_B = []
line_list_B = []
line_list_linije = []
with open(current) as f1:
for index1, line1 in enumerate(f1):
strings_B = ("p","P","t","T") #find lines which contain this str
line_list_B.append(line1) #put the line in line_list_B
if any(s in line1 for s in strings_B):
line_list_linije.append(line1)
print(line_list_linije)
index_list_B.append(index1) #positions of lines
with open(path1.join(name_output).format(index1), 'w') as output1:
for index1 in index_list_B:
print(line_list_B[index1])
output1.writelines([line_list_B[index11],
line_list_B[index1],','])
此代码通过'ODOGS/LAB'
目录中的文本文件进行搜索,并搜索是否有包含ceratain字符串的行。找到符合条件的所有行后,需要将它们写入新文件,但名称与输入文件相同。代码的那部分工作得很好。
我想将所有输出文件放入另一个目录path1
但是部分
with
声明无效。
我收到错误:
FileNotFoundError: [Errno 2] No such file or directory: 'sODOGS/lab_res_voicedzODOGS...
当with
语句为:
with open(name_output.format(index1), 'w') as output1:
然后我获取了根本文件夹中我不想要的所有文件。
我的问题是如何将输出文件放入path1
中的目录?
答案 0 :(得分:2)
形成输出路径时出错:
而不是
with open(path1.join(name_output).format(index1), 'w') as output1:
你想要
with open(os.path.join(path1, name_output), 'w') as output1: