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

2024-09-27 23:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

但是如何分开阅读呢?有人能告诉我怎么做吗?你知道吗


Tags: txt内容outputfbfrfilenameusersvr
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", ":")

您可以对文件进行迭代,并将行和索引用于您的优势;如下所示:

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

您可以使用文件文本:作为指示符来创建如下新文件:

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,这是您认为最好的分离数据的方法。在这里,我使用文件。。。你知道吗

相关问题 更多 >

    热门问题