读取具有多个分隔符的txt文件

时间:2018-04-18 09:52:43

标签: python append

我有一个seven columns and no headers的txt文件。前两列之间有一个空格,然后用分号作为分隔符。

以下是我在实现文件不均匀之前所尝试的内容:

 min17_q1 = open('ES 03-17.Last.txt', 'r')
 for line in min17_q1:
    fields = line.split(";")
    Date = fields[0]
    Time = fields[1]
    Open = fields[2]
    High = fields[3]
    Low = fields[4]
    Close = fields[5]
    Volume = fields[6]
    print(DateTime + Open + High + Low + Close + Volume)

如何阅读此文件,然后能够操作数据和/或将相同的文件附加到此文件?

3 个答案:

答案 0 :(得分:1)

要解析文件中的一行,请使用str.split(maxsplit=1)拆分第一个空格,然后再用分号分割:

for line in min17_q1:
    Date, fields = line.split(" ", 1)
    Time, Open, High, Low, Close, Volume = fields.split(';')
    print(Date + Time + Open + High + Low + Close + Volume)

要连接多个这些文件,请使用循环:

with open('output.txt') as outfile:
    # iterate over the files that need to be concatenated
    for infile in ['min17_q1', 'min17_q2', 'min17_q3']:
        with open(infile) as infile:
            # parse each line in the file and add it to the output file
            for line in infile:
                line = line.replace(' ', ';', 1)
                outfile.write(line)

在这种情况下,甚至不需要将每一行拆分成一个列表。我们可以用分号替换行中的第一个空格并将其写回。为此,我使用了str.replace(' ', ';', count=1)

答案 1 :(得分:1)

这可以通过一次拆分来完成:

for line in min17_q1:
    Date, Time, Open, High, Low, Close, Volume = line.replace(' ',';',1).split(';')
    print(Date + Time + Open + High + Low + Close + Volume)

和反向操作:

line = "%s %s;%s;%s;%s;%s;%s" % (Date, Time, Open, High, Low, Close, Volume)

答案 2 :(得分:1)

import re,os

outputfile = open('outfile.txt','a')

for all_files in os.listdir(os.getcwd()):
        if re.match(r'samp.*',all_files):
                min_file = open(all_files, 'r')
                for line in min_file:
                        fields=re.split(r'[ ;]',line.strip())
                        c=';'.join(fields)
                        #print c
                        outputfile.write(c)
                        outputfile.write('\n')
                min_file.close()
outputfile.close()