Python:将输入文件中的行的最后一个字追加到输出fi的行尾

2024-10-02 18:18:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有每日温度文件,我想合并成一个年度文件。
e、 g.输入文件

 Day_1.dat              
 Toronto  -22.5     
 Montreal -10.6  

 Day_2.dat            
 Toronto  -15.5  
 Montreal  -1.5  

 Day_3.dat      
 Toronto   -5.5
 Montreal  10.6  

所需的输出文件

^{pr2}$

这是目前为止我为程序的这一部分编写的代码:

    #Open files for reading (input) and appending (output)
    readFileObj = gzip.open(readfilename, 'r') #call built in utility to unzip file for    reading
    appFileObj = open(outFileName, 'a')
      for line in readfileobj:
        fileString = readFileObj.read(line.split()[-1]+'\n') # read last 'word' of each line
        outval = "" + str(float(filestring) +"\n" #buffer with a space and then signal end of line
        appFileObj.write(outval) #this is where I need formatting help to append outval

Tags: and文件toinforlineopendat
1条回答
网友
1楼 · 发布于 2024-10-02 18:18:21

在这里,^{}上的迭代允许我们迭代所有文件,每次取一行。现在我们在空白处分割每一行,然后使用城市名称作为键,在列表中存储相应的温度(或任何值)。在

import fileinput
d = {}
for line in fileinput.input(['Day_1.dat', 'Day_2.dat', 'Day_3.dat']):
    city, temp = line.split()
    d.setdefault(city, []).append(temp)

现在d包含:

^{pr2}$

现在,我们可以简单地遍历这个字典并将数据写入输出文件。在

with open('output_file', 'w') as f:
    for city, values in d.items():
       f.write('{} {}\n'.format(city, ' '.join(values)))

输出:

$ cat output_file 
Toronto -22.5 -15.5 -5.5
Montreal -10.6 -1.5 10.6

注意字典没有任何特定的顺序。因此,这里的输出可以是Montreal,然后是{}。如果顺序很重要,则需要使用collections.OrderedDict。在


代码的工作版本

d = {}
#Considering you've a list of all `gzip` files to be opened.
for readfilename in filenames:  
    #populate the dictionary by collecting data from each file
    with gzip.open(readfilename, 'r') as f:
        for line in f:
            city, temp = line.split()
            d.setdefault(city, []).append(temp)

#Now write to the output file
with open(outFileName, 'w') as f:
    for city, values in d.items():
       f.write('{} {}\n'.format(city, ' '.join(values)))

相关问题 更多 >