试图以更短的方式打开多个文本文件 [英] Trying to get shorter way of opening multiple text files

查看:113
本文介绍了试图以更短的方式打开多个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以更好,更简洁的方式打开多个JSON编码文本文件.当所有这些文件都存在时,很容易将其放在一个try代码中.

I'm trying to get a better, cleaner, and short way to open multiple JSON coded text files. When all of these files exist, it's easy to put it inside one try code.

但是,当文件不存在时,其余文件将不会打开. 此外,每个文本文件都包含一个词典,需要通过json.load导入到唯一词典中.

But when a file does not exist, the rest of the files won't be opened. Also, each text file contains a dictionary and needs to be imported to a unique dictionary through json.load.

我现在拥有的代码如下:

The code I have now is as follows:

dict1 = {}
while True:
    try:
        dict1 = json.load(open("temp/dict 1.txt"))
        break
    except (FileNotFoundError, IOError):
        break
    else:
        break

dict2 = {}
while True:
    try:
        dict2 = json.load(open("temp/dict 2.txt"))
        break
    except (FileNotFoundError, IOError):
        break
    else:
        break

dict3 = {}
while True:
    try:
        dict3 = json.load(open("temp/dict 3.txt"))
        break
    except (FileNotFoundError, IOError):
        break
    else:
        break

这个问题也和另一个问题挂在一起,在另一个主题中提出: 搜索更多内容比较多字典的一种优雅(较少代码)方式

This question also hangs together with another question, asked in another topic: Searching for a more elegant (less code) way to compare multiple dicts

也许对于我面临的这两个问题,还有另一种解决方案.

Perhaps there is another solution for both these problems I'm facing.

推荐答案

问题是您使用的中断将在第一次失败时停止.您应该做的是忽略该错误,并在文件不存在时继续下一个文件.我还建议您将字典存储在文件名引用的数组或字典中,而不要将其存储为单独的值.因此您的代码应如下所示:

The problem was that you were using break which would stop on first failure. What you should've done is to ignore the error and move on to the next file when the file didn't exist. I would also suggest you store your dictionaries in either an array or a dictionary referenced by the file name instead of as separate values. So your code would look something like this:

filenames = ['path1', 'path2']
loaded = {} 
for fp in filenames:
    try:
        with open(fp, 'r') as pointer:
            loaded[fp] = json.load(pointer)
    except (FileNotFoundError, IOError):
        continue

这篇关于试图以更短的方式打开多个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆