![](/img/trans.png)
[英]How to read text file on python and get values from it to set it on an array
[英]How to read a sorted and set text file in Python?
我是 python 的新手,遇到了我正在讀取文本文件並刪除不需要的內容並使用 sorted-set 寫入新文本文件的問題。 然后我需要閱讀新的文本文件並繼續進行下一步編碼。 但是當我讀取文件時,它的讀數是從新文本文件中跳過最后 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
您檢查子字符串的條件不正確:
if 'blab: name=' and 'blab1' in line:
將分別檢查行中的 'blab 'blab: name='
和'blab1' in line
(條件的兩個部分都需要成立)。 你想要的是:
if 'blab: name=' in line or 'blab1' in line:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.