首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多文件处理

多文件处理
EN

Stack Overflow用户
提问于 2012-08-04 15:11:20
回答 1查看 693关注 0票数 0

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

*,当操作完成时,我会不断地重复一个汉字。那我哪里出错了?谢谢lot!*

以下是代码:

代码语言:javascript
复制
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!!")
EN

回答 1

Stack Overflow用户

发布于 2012-08-04 18:13:14

如果我正确地理解了这个问题,那么这个问题就会奏效:

代码语言:javascript
复制
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_itemsline2_items中切换for zip_entry in zip_longest(line1_items, line2_items, fillvalue='FILL_VALUE'):

在input2中,每一行的第一项将被忽略。

我的测试数据如下:

input1.txt:

代码语言:javascript
复制
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
2, 22, 222, 2222

input2.txt:

代码语言:javascript
复制
z, a, b, c, d, e, f, g, h, i, j, k
z, a, aaa, aaaa

结果:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11809648

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档