【问题标题】:os.path.join issue Windowsos.path.join 问题 Windows
【发布时间】:2017-09-27 20:15:33
【问题描述】:

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

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

基本上,以下os.path.join 代码在以下部分中似乎无法在 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())

【问题讨论】:

    标签: python python-2.7 os.path


    【解决方案1】:

    我认为这行在 Windows 上不好:

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

    '/' 上的拆分根本不会拆分。您应该改用 os.path.sep。

    我认为 os.path.join 反应如此混乱,因为您尝试加入的第二部分已经是完整的文件路径(因为拆分失败)。

    【讨论】:

    • 感谢您的快速回复,我会考虑您的建议。谢谢!
    猜你喜欢
    • 2021-08-18
    • 2011-01-26
    • 2020-01-01
    • 2011-06-26
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2011-01-14
    • 2011-12-13
    相关资源
    最近更新 更多