Python 多文件处理

Python 多文件处理,python,exception-handling,python-3.x,file-handling,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/

我试图从每个文件中获取信息,并使用它创建一个新文件。每个文件都有一行,由一系列数字组成。我希望一个文件的每一行与另一个文件的每一行对齐,然后取一个文件行中的每一个数字,使另一个数字与另一个文件中另一行的位置相同。文件“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!!")

如果我正确理解了这个问题,这应该可以做到:

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_值替换为要插入的内容

如果需要第一个项目来自input2.txt而不是input1.txt,请将
line1\u项目
line2\u项目
切换到
中,以便在zip\u中输入最长的zip\u项目(line1\u项目,line2\u项目,fillvalue='FILL\u值'):

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

问题不清楚,是每个文件中只有一行,还是每个文件中有多行?如果每个文件中有多行,那么每行上是否有多个数字?如果一行上有多个数字,分隔符是什么?我几乎没有阅读你的代码,因为似乎写一些简短的东西来完成问题文本部分描述的工作会更容易。很抱歉造成混淆。我从中提取的两个文件各有多行。每行有多个数据点,每个数据点由逗号和空格分隔。我试图将一个文件的第一行和另一个文件的第一行进行匹配,然后将EODP.txt中的数据点1和Volume.txt中的数据点2以及两行中的每一个其他数据进行匹配,使相对位置错开。我希望在后续的每一行中都重复此操作。每个文件都有相同的行数,但每行使用的数据点数不一定相同。希望有帮助,谢谢!交错点的意思是:文件卷,第1行,第2点和文件EODP,第1行,第1点。然后是文件卷第1行第3点和文件EODP第1行第2点。重复整个长度的文件EODP第1行,该行应具有lenth len(卷第1行)-1。此问题可能存在大量近似重复项。只需搜索“python合并文件”。