如何在Python中读取已排序和设置的文本文件?

问题描述 投票:0回答:1

[我是python的新手,我一直在解决这个问题,我正在读取文本文件并删除不需要的文件,并使用排序集将其写入新的文本文件。那么我需要阅读新的文本文件,并继续进行下一个编码。但是,当我读取文件时,其读取内容却从新文本文件中跳过了最后40条奇数行。

请在下面找到我的编码

f3 = open("data/new.txt", "w")
uniqueperm = []
with open("data/read1.txt", "r") as ins:
    d = ins.readlines()
    for line in d:
    #print(line)

        if 'blab: name=' and 'blab1' in line:

            line = str(line.replace("blab: name= ", "").replace("'", "").replace("\n", ""))
            line = str(line.replace("blab1: ", "").replace("'", "").replace("\n", ""))
            #print(line)
            uniqueperm.append(line)
            #print((line))

for pop in (sorted(set(uniqueperm))):
#print(pop)
f3.write(pop + "\n")

packages = os.listdir("./data/")
inss = open("data/new.txt", 'r').read().split("\n")
print(inss)

output inss从新文本文件中逐行读取,但是跳过新文本文件中的最后40条奇数行。请有人帮助我解决这个问题。在此先感谢:)

#read1.txt file contains 

blab1: cool.add.WEATHER_ALL
blab1: warm:add.WEATHER_EVERYWHERE
blab: name= hello.add.COPY_HI
blab: name= hello.add.ACCESS_HELLO
blab: name= hello.add.ADD_HI
blab: name= hello.add.WRITE_HI
.
.
.
#it also include repeated data as above so i used set() option so the duplicates are removed before writing to new.txt file 

#new.txt file contains

hello.add.ACCESS_HELLO
hello.add.ADD_HI
hello.add.COPY_HI
hello.add.WRITE_HI
cool.add.WEATHER_ALL
warm.add.WEATHER_EVERYWHERE
.
.
.

#new.txt file contains all the data from read1.txt

#when i read this new.txt file in terminal the output is

hello.add.ACCESS_HELLO
hello.add.ADD_HI
hello.add.COPY_HI
hello.add.WRITE_HI
cool.add.WEATHER_ALL

#remaining its skipping or not reading to further proceed
python python-3.x python-2.7 text-files read-write
1个回答
1
投票

您检查子字符串的条件不正确:

if 'blab: name=' and 'blab1' in line:

将分别检查'blab: name=''blab1' in line(并且条件的[[both部分需要保持为真”)。您想要的是:

if 'blab: name=' in line or 'blab1' in line:
© www.soinside.com 2019 - 2024. All rights reserved.