【发布时间】:2017-08-10 06:02:27
【问题描述】:
我有多个带有 ID 和值的 *.txt 文件,我想创建一个唯一的字典。但是,某些 ID 在某些文件中重复,对于这些 ID,我想连接这些值。这是两个文件的示例(但我有一堆文件,所以我认为我需要 glob.glob):(注意某个文件中的所有“值”都具有相同的长度,所以我可以添加“-”为len(value) 多次丢失。
文件 1
ID01
Hi
ID02
my
ID03
ni
文件 2
ID02
name
ID04
meet
ID05
your
Desire 输出:(注意当没有重复的 ID 时,我想添加 'Na' 或 '-',并连接相同的 len(value))这是我的输出:
ID01
Hi----
ID02
myname
ID03
ni----
ID04
--meet
ID05
--your
我只想将输出存储在字典中。另外,我想如果我在打开文件时打印文件,我可以知道哪些文件是依次打开的,对吧?
这就是我所拥有的:(到目前为止,我无法连接我的值)
output={}
list = []
for file in glob.glob('*.txt'):
FI = open(file,'r')
for line in FI.readlines():
if (line[0]=='I'): #I am interested in storing only the ones that start with I, for a future analysis. I know this can be done separating key and value with '\t'. Also, I am sure the next lines (values) does not start with 'I'
ID = line.rstrip()
output[ID] = ''
if ID not in list:
list.append(ID)
else:
output[ID] = output[ID] + line.rstrip()
if seqs_name in list:
seqs[seqs_name] += seqs[seqs_name]
print (file)
FI.close()
print ('This is your final list: ')
print (list) #so far, I am getting the right final list, with no repetitive ID
print (output) #PROBLEM: the repetitive ID, is being concatenated twice the 'value' in the last file read.
另外,ID不重复时如何添加'-'?非常感谢您的帮助。
总结:当键在另一个文件中重复时,我无法连接值。如果 key 不重复,我想添加 '-' ,这样我以后可以打印文件名并知道某个 ID 在哪个文件中没有值。
【问题讨论】:
标签: python dictionary text-files glob string-concatenation