如何使用python读取.txt文件的内容?

时间:2016-02-22 08:18:22

标签: python regex python-2.7 file

output_filename = r"C:\Users\guage\Output.txt"
RRA:
GREQ-299684_6j 
GREQ-299684_6k 
CZM:
V-GREQ-299684_6k 
V-GREQ-299524_9 
F_65624_1 
R-GREQ-299680_5 
DUN:
FB_71125_1 
FR:
VQ-299659_18 
VR-GREQ-299659_19 
VEQ-299659_28 
VR-GREQ-299659_31 
VR-GREQ-299659_32 
VEQ-299576_1 
GED:
VEQ-299622_2 
VR-GREQ-299618_13 
VR-GREQ-299559_1 
VR-GREQ-299524_14
FB_65624_1 
VR-GREQ-299645_1 
MNT:
FB_71125_1 
FB_71125_2 
VR-534_4 

以上是.txt文件的内容。我怎么能单独阅读它的内容。例如 -

RRA:VR-GREQ-299684_6j VR-GREQ-299684_6k VR-GREQ-299606_3 VR-GREQ-299606_4 VR-GREQ-299606_5 VR-GREQ-299606_7 

并将其保存在变量或类似的变量中。后来我想单独阅读CZM等等。我做了如下。

with open(output_filename, 'r') as f:
        excel = f.read()

但如何单独阅读?谁能告诉我怎么做?

4 个答案:

答案 0 :(得分:3)

这样的事情:

def read_file_with_custom_record_separator(file_path, delimiter='\n'):
    fh = open(file_path)
    data = ""
    for line in fh:
        if line.strip().endswith(delimiter) and data != "":
            print "VARIABLE:\n<", data, ">\n"
            data = line
        else:
            data += line
    print "LAST VARIABLE:\n<", data, ">\n"

然后:

read_file_with_custom_record_separator("input.txt", ":")

答案 1 :(得分:2)

您可以使用文件文本:作为指标来创建这样的新文件:

savefilename = ""
with open(filename, 'r') as f:
    for line in f:
        line = line.strip() # get rid of the unnecessary white chars
        lastchar = line[-1:] # get the last char
        if lastchar == ":": # if the last char is ":"
            savefilename = line[0:-1] # get file name from line (except the ":")
            sf = open(savefilename + ".txt", 'w') # create a new file
        else:
            sf.write(line + "\n") # write the data to the opened file

然后你应该得到文件集合:

RRA.txt
CZM.txt
DUN.txt
# etc

包含所有适当的数据:

RRA.txt

VR-GREQ-299684_6j
VR-GREQ-299684_6k
VR-GREQ-299606_3
VR-GREQ-299606_4
VR-GREQ-299606_5
VR-GREQ-299606_7

CZM.txt

VR-GREQ-299684_6k
VR-GREQ-299606_6
VR-GREQ-299606_8
VR-GREQ-299640_1
VR-GREQ-299640_5
VR-GREQ-299524_9
FB_65624_1
VR-GREQ-299680_5

DUN.txt

FB_71125_1

# and so on

您可以将sf = opensf.write替换为您最适合分隔数据的方式。在这里,我使用文件......

答案 2 :(得分:0)

您可以迭代文件并使用线条和索引来获得优势;像这样的东西:

with open(output_filename, 'r') as f:
    for index, line in enumerate(f):
        # here you have access to each line and its index
        # so you can save any number of lines you wish

答案 3 :(得分:0)

如何将其读入列表,然后根据需要处理其元素

>>> f = open('myfile.txt', 'r').readlines()
>>> len(f)
46
>>> f[0]
RRA:

>>> f[-1]
VR-GREQ-299534_4

>>> f[:3]
['RRA:\n', 'VR-GREQ-299684_6j \n', 'VR-GREQ-299684_6k \n']
>>>
>>> [l for l in f if l.startswith('FB_')]
['FB_65624_1 \n', 'FB_71125_1 \n', 'FB_69228_1 \n', 'FB_65624_1 \n', 'FB_71125_1 \n', 'FB_71125_2 \n']
>>>