簡體   English   中英

Python文件內容以空行插入字典

[英]Python file contents to dictionary with empty lines

嗨,朋友,我有以下格式的文件

#temp.txt

fruit apple
vegi  leafy

我正在嘗試使用以下代碼讀取文件並將元素推入字典中

with open("temp.txt") as fd:
    d = dict(line.rstrip().split(None, 1) for line in fd)

說如果我的輸入文件在文件末尾有新的空行,則會出現以下錯誤

ValueError: dictionary update sequence element #2 has length 0; 2 is required

有人可以讓我知道如何解決這個問題嗎?

with open("temp.txt") as fd:
    d = dict(line.rstrip().split(None, 1) for line in fd if not line == '\n')

由於您的temp.txt文件中包含空行,因此當您嘗試剝離並拆分行時它將失敗,並且不會導致兩個參數。

盡管不那么優雅,但您可能需要測試每行有兩個參數,否則,如果其中一行只有一個參數,它也會失敗。 例如,您可以執行以下操作:

with open("temp.txt") as fd:
    d = dict(line.rstrip().split(None, 1) for line in fd if len(line.rstrip().split(None, 1)) == 2)

然后,這將與以下文件一起使用,其中它將忽略第二個fruit條目:

fruit apple

vegi  leafy
fruit

另一種方法是在with

try:
    -your statement-
except ValueError:
    continue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM