I have this text file and let's say it contains 10 lines.
Bye
Hi
2
3
4
5
Hi
Bye
7
Hi
Every time it says "Hi" and "Bye" I want it to be removed except for the first time it was said.
My current code is (yes filename is actually pointing towards a file, I just didn't place it in this one)
text_file = open(filename)
for i, line in enumerate(text_file):
if i == 0:
var_Line1 = line
if i = 1:
var_Line2 = line
if i > 1:
if line == var_Line2:
del line
text_file.close()
It does detect the duplicates, but it takes a very long time considering the amount of lines there are, but I'm not sure on how to delete them and save it as well
You could use dict.fromkeys to remove duplicates and preserve order efficiently:
with open(filename, "r") as f:
lines = dict.fromkeys(f.readlines())
with open(filename, "w") as f:
f.writelines(lines)
Idea from Raymond Hettinger
Using a set & some basic filtering logic:
with open('test.txt') as f:
seen = set() # keep track of the lines already seen
deduped = []
for line in f:
line = line.rstrip()
if line not in seen: # if not seen already, write the lines to result
deduped.append(line)
seen.add(line)
# re-write the file with the de-duplicated lines
with open('test.txt', 'w') as f:
f.writelines([l + '\n' for l in deduped])
I have a text file that with multiple lines and I'm trying to assign turn every line into a string and assign them into a variable separately. The code looks something like this at the moment:
with open('config.txt', 'r') as f:
file_name = ''.join(f.readlines()[0:1])
Runstart = ''.join(f.readlines()[1:2])
Runend = ''.join(f.readlines()[2:3])
But it doesn't read anything after the first line. What am I doing wrong here and how do I fix it? The goal is to give a name for every line. Alternative methods are welcomed.
Thanks.
You don't need all these slices and indices. Just use readline:
with open('config.txt', 'r') as f:
file_name = f.readline()
Runstart = f.readline()
Runend = f.readline()
You can treat the file as an iterator.
from itertools import islice
with open('config.txt', 'r') as f:
file_name, Runstart, Runend = (x.rstrip() for x in islice(f, 3))
not sure if this helps but this is what I understand from your question:
with open('config.txt', 'r') as f:
for line in f:
thisList = line.split(' ')
string = ''
file_name = thisList[0]
Runstart = thisList[1]
Runend = thisList[2]
print(file_name, Runstart, Runend)
with open("list.txt") as f:
lst = (f)
print(lst)
for h in lst:
print(lst[h])
In a loop i want to open a file take 1st line as a var and do something with selenium and then take another line and do the selenium stuff again until last line.
trying since evening only getting errors. like list indices must be integers or slices, not str.
Why not this :
with open("list.txt") as f:
for line in f:
print(line)
# do selenium stuff
if somecondition :
break
with open("list.txt", 'r') as f:
lines = f.readlines()
for line in Lines:
# do smth here
Looks like you want to read the data in the file list.txt and want to print out the list with each line of file list.txt as an element of lst. You would want to do that like-
lst = []
with open("list.txt") as f:
for new in f:
if new != '\n':
addIt = new[:-1].split(',')
lst.append(addIt)
for h in lst:
print(lst[h])
You can try something like this as well
lst = open("list.txt").read().split('\n')
for each in lst:
print(each)
I have this data in my sample.txt file:
A2B3,32:45:63
A4N6,17:72:35
S2R3,13:14:99
What I want to do is to put those data in an array but I'm having problems separating those with commas.
My code goes like this:
with open('sample.txt', 'r') as f:
for line in f:
x = f.read().splitlines()
print(x)
And the output goes like this:
['A2B3,32:45:63','A4N6,17:72:35','S2R3,13:14:99']
I altered my code in different ways to separate those two variables with commas but I can't seem to make it work. Can someone help me achieve this output?
['A2B3','32:45:63','A4N6','17:72:35','S2R3','13:14:99']
use line.split(',') to seperate the line at the ",".
x = []
with open('sample.txt', 'r') as f:
for line in f:
for j in line.split(','):
x.append(j.split('\n')[0])
print(x)
Use this code, which splits the lines into a list like you have, and then splits those items at the comma.
filename = "sample.txt"
with open(filename) as file:
lines = file.read().split("\n")
output = []
for l in lines:
for j in l.split(","):
output.append(j)
print(output)
Output:
['A2B3', '32:45:63', 'A4N6', '17:72:35', 'S2R3', '13:14:99']
You probably could just do:
data = list()
with open('sample.txt', 'r') as f:
for line in f.readlines():
data.append(line)
And you should end up with list of appended lines. It's also faster on big files than just .splitlines() since .readlines() is implemented in C and doesn't load whole file in memory.
yes, it's very simple...
after separate all line, you get list look like
['A2B3,32:45:63','A4N6,17:72:35','S2R3,13:14:99']
then after again you separate that each element by comma(,) and add it into new list like
list_a = ['A2B3,32:45:63','A4N6,17:72:35','S2R3,13:14:99']
final_list = []
for i in list_a:
part_1, part_2 = i.split(',')
final_list.append(part_1)
final_list.append(part_2)
print(final_list)
And it will give your desire output like
['A2B3','32:45:63','A4N6','17:72:35','S2R3','13:14:99']
it is not a redundant way but for you very easy to understand
Thank You :)
Here you go, just iterating once over the lines:
res = []
with open('sample.txt', 'r') as f:
for line in f:
res += line.strip().split(",")
print(res)
Gives:
['A2B3', '32:45:63', 'A4N6', '17:72:35', 'S2R3', '13:14:99']
Though I wonder why you'd want to have everything in a list, I think you are missing the link between the items, maybe could be more useful to keep them in tuples like this:
res = []
with open('sample.txt', 'r') as f:
for line in f:
res.append(tuple(line.strip().split(",")))
print(res)
Gives:
[('A2B3', '32:45:63'), ('A4N6', '17:72:35'), ('S2R3', '13:14:99')]
FMPOV this result is better to go along. But nevermind, I guess, you'll find your solution from one of those poseted here.
x = [i.replace("\n","").split(',')for i in open('data.txt', 'r')]
print(x)
print(x[0][1])
I have text file like this:
test:Player:232.746860697:76.0:206.635144909
b2:Player2:245.330907228:77.0:207.785677928
b3:Player4:236.52764454:76.0:203.95246227
b45:Player33:240.496564206:77.0:205.574781979
I want to delete line that starts with i.e. test:Player, I already made this, but I don't know how to delete that line? Here's my code so far:
pluginlokacija2 = os.path.realpath("%s/plugins"%os.getcwd())
textfile = open("%s/CreativePoints/Data/plotovi.txt"%pluginlokacija2, 'r')
for line in textfile.readlines():
if line.startswith("%s:%s"%(args[1], sender.getName())):
#delete that line, how?
Thanks in advance! :)
# Filter unwanted lines
a = filter(lambda x: not x.startswith("%s:%s"%(args[1], sender.getName())), \
textfile.readlines())
# Write filtered lines to file
textfile.seek(0)
textfile.truncate()
textfile.writelines(list(x.strip() for x in a))
textfile.close()
And don't forget to open the file as readable and writable (r+ instead of r).
To make writes reliable put all operations on file into context manager:
from itertools import ifilterfalse
with open('/home/reserve/Desktop/s.txt', 'r+') as f:
b = ifilterfalse(lambda x: x.startswith("%s:%s"%(args[1],sender.getName())),\
f.readlines())
f.seek(0)
f.truncate()
f.writelines(list(x.strip() for x in b))
f = open("a.txt","r")
lines = f.readlines()
f.close()
f = open("a.txt","w")
for line in lines:
if not line.startswith('test:Player'):
f.write(line)
print(line)
f.close()
Hope this helps. Modify according to your requirements.