多文件处理

时间:2012-08-04 15:11:21

标签: python exception-handling python-3.x file-handling

我正在尝试从每个文件中获取信息并使用它来创建新文件。每个文件都有一行由一系列数字组成。我希望一个文件的每一行与另一个文件的每一行对齐,然后将每个数字放在一个文件的一行中,以满足另一个文件中另一行相同位置的另一个数字。文件'Volume.txt'使每一行移位一个点(因此代码为k = j + 1)。

* 操作完成后,我不断重复一个汉字。那我哪里出错了?非常感谢! *

以下是代码:

e = open('C:/Users/MC/Desktop/EODP.txt', 'r')
v = open('C:/Users/MC/Desktop/Z/Volume.txt', 'r')
n = open('C:/Users/MC/Desktop/vovere.txt', 'w')

m = 0 #Used later for letting me know that the first line in the new file completed

for i in range(0, 3256):  # there are 3257 lines per the two files EOPD and Volume
    l = []                # create a list to put data in during operation
    er = e.readline()     #
    es = er.split(', ')   # create a list the data from that line of file
    vr = v.readline()     #
    vs = vr.split(', ')   # same
    for  j in range(len(es)):
        k = j + 1         #  file Volume is shifted one point ahead
        try:
            if float(vs[k]) == 0.0:
                vovere = 0.0             # vovere is the name of the output for each point
            elif vs[k] == '' or vs[k] == ' ':
                vovere = 0.0
            else:
                vovere = float(es[j])/float(vs[k])
        except ValueError:         #kept getting this error: some points weren't numbers
            vovere = 0.0       
        except IndexError:         # Each file didn't always exactly equal in line length
            vovere = 0.0
        la = l.append(float(vovere)) #Creates the list for each new line in new file
    ls = str(la)
    l1 = ls.replace('[', '')    # Taking away extra notations so the new file is a little 
    l2 = l1.replace(']', '')    # more clean and can be put into other programs 
    n.write(l2)
    if m == 0:                 # From here on out is just for me, not necessary**
        print("The first line is done!")
        m += 1
    else:
        pass

e.close()                      #** Except these of course
print(e.closed)
print("Yes, EOPD.txt is closed")
v.close()
print(v.closed) 
print("Yes, Volume.txt is closed")
n.close()
print(n.closed) 
print("Yes, vovere.txt is now ready for further manipulation!!")

1 个答案:

答案 0 :(得分:0)

如果我正确地理解了这个问题,那应该可以解决问题:

from itertools import zip_longest # If this was python 2.x import izip_longest instead

if __name__ == '__main__':
    input1_lines = []
    input2_lines = []

    # Read all the input from first file
    with open('./input1.txt', 'r') as input1:
        input1_lines = input1.readlines()

    # Read all the input from first file
    with open('./input2.txt', 'r') as input2:
        input2_lines = input2.readlines()

    # Go through all the lines
    output_lines = []
    for line_number_index in range(len(input1_lines)):
    # For each line in each input file make a list of items and remove line breaks
        line1_items = str(input1_lines[line_number_index]).replace('\n', '').split(', ')
        line2_items = str(input2_lines[line_number_index]).replace('\n', '').split(', ')[1:]

        # Go through the item lists and merge them, fill empty spots with fillvalue if there are more items in one of the lists
        this_output_line = []
        for zip_entry in zip_longest(line1_items, line2_items, fillvalue='FILL_VALUE'):
            this_output_line.append(', '.join(zip_entry))
        output_lines.append(', '.join(this_output_line))

    # Write out the file
    with open('./output.txt', 'w') as output_file:
        for line in output_lines:
            output_file.write('%s\n' % line)

将FILL_VALUE替换为您要插入的任何内容,如果其中一行中的项目多于另一行中的项目。

如果您需要第一个项目来自input2.txt而不是input1.txt,请在line1_items

中切换line2_itemsfor zip_entry in zip_longest(line1_items, line2_items, fillvalue='FILL_VALUE'):

input2是将忽略每一行的第一项的那一行。

我的测试数据:

input1.txt:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
2, 22, 222, 2222

input2.txt:

z, a, b, c, d, e, f, g, h, i, j, k
z, a, aaa, aaaa

结果:

0, a, 1, b, 2, c, 3, d, 4, e, 5, f, 6, g, 7, h, 8, i, 9, j, 10, k
2, a, 22, aaa, 222, aaaa, 2222, FILL_VALUE