os.path.join问题Windows

时间:2017-09-27 20:15:34

标签: python python-2.7 os.path

我遇到了os.path.join和Windows系统的一些问题。我创建了一个脚本,以递归方式读取包含非结构化JSON数据的文件,创建名为“converted_json”的目录,并以结构化格式将每个非结构化JSON文件的内容打印到“converted_json”目录中的新文件中。

我在macOS上测试了下面的脚本,在执行时,结构化的JSON数据被打印到新文件,新文件被输出到“converted_json”目录。但是,当我在Windows系统上执行脚本时,JSON数据将打印到新文件,但文件不会输出到“converted_json”目录。

基本上,以下os.path.joi n代码在以下部分似乎不适用于Windows:

conv_json = open(os.path.join(converted_dir, str(file_name[-1]) + '_converted'), 'wb')

创建文件,但它们不存储在converted_dir变量指定的“converted_json”目录中。

以下输出来自打印“conv_json”变量:

打开文件'C:\ Users \ test \ Desktop \ test \ file_name.json.gz.json_converted',模式'wb'位于0x0000000002617930

如上所示,“conv_json”变量中包含的文件路径不包含“converted_json”目录(应该使用os.path.join和converted_dir变量。

有关如何将结构化数据输出到“converted_json”目录的任何帮助将不胜感激。

以下代码:

argparser = argparse.ArgumentParser()
argparser.add_argument('-d', '--d', dest='dir_path', type=str, default=None, required=True, help='Directory path to Archive/JSON files')
args = argparser.parse_args()
dir_path = args.dir_path


converted_dir = os.path.join(dir_path, 'converted_json')
os.mkdir(converted_dir, 0777)

for subdir1, dirs1, files1 in os.walk(dir_path):
    for file in files1:

        try:
            if file.endswith(".json"):
                file = open(os.path.join(subdir1, file))
                file_name = str.split(file.name, '/')

                conv_json = open(os.path.join(converted_dir, str(file_name[-1]) + '_converted'), 'wb')

                conv_json.write('#################################################################################################################################')
                conv_json.write('\n')
                conv_json.write('File Name: ' + file_name[-1])
                conv_json.write('\n')
                conv_json.write('#################################################################################################################################')
                conv_json.write('\n')

                parsed_json = json.load(file)
                s = cStringIO.StringIO()
                pprint.pprint(parsed_json, s)

                conv_json.write(s.getvalue())

                conv_json.close()

        except:
            print 'JSON Files Not Found'

print 'JSON Processing Completed: ' + str(datetime.datetime.now())

1 个答案:

答案 0 :(得分:0)

我认为这条线在Windows上很糟糕:

file_name = str.split(file.name, '/')

分拆' /'根本不会分裂。你应该使用os.path.sep。

我认为os.path.join反应如此令人困惑,因为你尝试加入的第二部分已经是一个完整的文件路径(因为拆分失败了)。