Deleting line that startswith in txt file? - python

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.

Related

Removing lines in one file that are present in another file using python

I am stuck with removing lines that are present a file using the lines present another file in python. I am using two for loops for string matching but it gives duplicate lines on second itration of loop. Is there any other ways to do it. Thanks
with open('results.csv','r+') as source:
lines = source.readlines()
f = open('results_comments.csv','r')
line = f.readlines()
for l in line:
for L in lines:
if L!=l:
source.write(L)
f.close()
You can try:
with open('results.csv','r') as source:
lines_src = source.readlines()
with open('results_comments.csv','r') as f:
lines_f = f.readlines()
destination = open("destination.csv","w")
for data in lines_src:
if data not in lines_f:
destination.write(data)
destination.close()
Your variable names are confusing so I've renamed a couple. I think you'll need to open a new file for writing the results (at least that will make it clearer what you're trying to do). You can rename the file afterwards if you want the same name.
with open('results.csv','r+') as source:
filter_lines = source.readlines()
with open('results_comments.csv','r') as f:
lines = f.readlines()
with open('target.csv', 'w') as target:
for line in lines:
if line not in filter_lines:
target.write(line)
with open('results.csv','r+') as source:
lines = source.readlines()
f = open('results_comments.csv','r')
line = f.readlines()
line = filter(lambda x : x not in lines, line)
f.write('\n'.join(line))
f.close()

Copying content of file into another file in Python [duplicate]

I would like to copy certain lines of text from one text file to another. In my current script when I search for a string it copies everything afterwards, how can I copy just a certain part of the text? E.g. only copy lines when it has "tests/file/myword" in it?
current code:
#!/usr/bin/env python
f = open('list1.txt')
f1 = open('output.txt', 'a')
doIHaveToCopyTheLine=False
for line in f.readlines():
if 'tests/file/myword' in line:
doIHaveToCopyTheLine=True
if doIHaveToCopyTheLine:
f1.write(line)
f1.close()
f.close()
The oneliner:
open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])
Recommended with with:
with open("in.txt") as f:
lines = f.readlines()
lines = [l for l in lines if "ROW" in l]
with open("out.txt", "w") as f1:
f1.writelines(lines)
Using less memory:
with open("in.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
if "ROW" in line:
f1.write(line)
readlines() reads the entire input file into a list and is not a good performer. Just iterate through the lines in the file. I used 'with' on output.txt so that it is automatically closed when done. That's not needed on 'list1.txt' because it will be closed when the for loop ends.
#!/usr/bin/env python
with open('output.txt', 'a') as f1:
for line in open('list1.txt'):
if 'tests/file/myword' in line:
f1.write(line)
Just a slightly cleaned up way of doing this. This is no more or less performant than ATOzTOA's answer, but there's no reason to do two separate with statements.
with open(path_1, 'a') as file_1, open(path_2, 'r') as file_2:
for line in file_2:
if 'tests/file/myword' in line:
file_1.write(line)
Safe and memory-saving:
with open("out1.txt", "w") as fw, open("in.txt","r") as fr:
fw.writelines(l for l in fr if "tests/file/myword" in l)
It doesn't create temporary lists (what readline and [] would do, which is a non-starter if the file is huge), all is done with generator comprehensions, and using with blocks ensure that the files are closed on exit.
f=open('list1.txt')
f1=open('output.txt','a')
for x in f.readlines():
f1.write(x)
f.close()
f1.close()
this will work 100% try this once
in Python 3.10 with parenthesized context managers, you can use multiple context managers in one with block:
with (open('list1.txt', 'w') as fout, open('output.txt') as fin):
fout.write(fin.read())
f = open('list1.txt')
f1 = open('output.txt', 'a')
# doIHaveToCopyTheLine=False
for line in f.readlines():
if 'tests/file/myword' in line:
f1.write(line)
f1.close()
f.close()
Now Your code will work. Try This one.

How to read one particular line from .txt file in python?

I know I can read the line by line with
dataFile = open('myfile.txt', 'r')
firstLine = dataFile.readline()
secondLine = dataFile.readline()
...
I also know how to read all the lines in one go
dataFile = open('myfile.txt', 'r')
allLines = dataFile.read()
But my question is how to read one particular line from .txt file?
I wish to read that line by its index.
e.g. I want the 4th line, I expect something like
dataFile = open('myfile.txt', 'r')
allLines = dataFile.readLineByIndex(3)
Skip 3 lines:
with open('myfile.txt', 'r') as dataFile:
for i in range(3):
next(dataFile)
the_4th_line = next(dataFile)
Or use linecache.getline:
the_4th_line = linecache.getline('myfile.txt', 4)
From another Ans
Use Python Standard Library's linecache module:
line = linecache.getline(thefilename, 33)
should do exactly what you want. You don't even need to open the file -- linecache does it all for you!
You can do exactly as you wanted with this:
DataFile = open('mytext.txt', 'r')
content = DataFile.readlines()
oneline = content[5]
DataFile.close()
you could take this down to three lines by removing oneline = content[5] and using content[5] without creating another variable (print(content[5]) for example) I did this just to make it clear that content[5] must be a used as a list to read the one line.

Insert string at the beginning of each line

How can I insert a string at the beginning of each line in a text file, I have the following code:
f = open('./ampo.txt', 'r+')
with open('./ampo.txt') as infile:
for line in infile:
f.insert(0, 'EDF ')
f.close
I get the following error:
'file' object has no attribute 'insert'
Python comes with batteries included:
import fileinput
import sys
for line in fileinput.input(['./ampo.txt'], inplace=True):
sys.stdout.write('EDF {l}'.format(l=line))
Unlike the solutions already posted, this also preserves file permissions.
You can't modify a file inplace like that. Files do not support insertion. You have to read it all in and then write it all out again.
You can do this line by line if you wish. But in that case you need to write to a temporary file and then replace the original. So, for small enough files, it is just simpler to do it in one go like this:
with open('./ampo.txt', 'r') as f:
lines = f.readlines()
lines = ['EDF '+line for line in lines]
with open('./ampo.txt', 'w') as f:
f.writelines(lines)
Here's a solution where you write to a temporary file and move it into place. You might prefer this version if the file you are rewriting is very large, since it avoids keeping the contents of the file in memory, as versions that involve .read() or .readlines() will. In addition, if there is any error in reading or writing, your original file will be safe:
from shutil import move
from tempfile import NamedTemporaryFile
filename = './ampo.txt'
tmp = NamedTemporaryFile(delete=False)
with open(filename) as finput:
with open(tmp.name, 'w') as ftmp:
for line in finput:
ftmp.write('EDF '+line)
move(tmp.name, filename)
For a file not too big:
with open('./ampo.txt', 'rb+') as f:
x = f.read()
f.seek(0,0)
f.writelines(('EDF ', x.replace('\n','\nEDF ')))
f.truncate()
Note that , IN THEORY, in THIS case (the content is augmented), the f.truncate() may be not really necessary. Because the with statement is supposed to close the file correctly, that is to say, writing an EOF (end of file ) at the end before closing.
That's what I observed on examples.
But I am prudent: I think it's better to put this instruction anyway. For when the content diminishes, the with statement doesn't write an EOF to close correctly the file less far than the preceding initial EOF, hence trailing initial characters remains in the file.
So if the with statement doens't write EOF when the content diminishes, why would it write it when the content augments ?
For a big file, to avoid to put all the content of the file in RAM at once:
import os
def addsomething(filepath, ss):
if filepath.rfind('.') > filepath.rfind(os.sep):
a,_,c = filepath.rpartition('.')
tempi = a + 'temp.' + c
else:
tempi = filepath + 'temp'
with open(filepath, 'rb') as f, open(tempi,'wb') as g:
g.writelines(ss + line for line in f)
os.remove(filepath)
os.rename(tempi,filepath)
addsomething('./ampo.txt','WZE')
f = open('./ampo.txt', 'r')
lines = map(lambda l : 'EDF ' + l, f.readlines())
f.close()
f = open('./ampo.txt', 'w')
map(lambda l : f.write(l), lines)
f.close()

Python, add items from txt file into a list

Say I have an empty list myNames = []
How can I open a file with names on each line and read in each name into the list?
like:
> names.txt
> dave
> jeff
> ted
> myNames = [dave,jeff,ted]
Read the documentation:
with open('names.txt', 'r') as f:
myNames = f.readlines()
The others already provided answers how to get rid of the newline character.
Update:
Fred Larson provides a nice solution in his comment:
with open('names.txt', 'r') as f:
myNames = [line.strip() for line in f]
f = open('file.txt','r')
for line in f:
myNames.append(line.strip()) # We don't want newlines in our list, do we?
names=[line.strip() for line in open('names.txt')]
#function call
read_names(names.txt)
#function def
def read_names(filename):
with open(filename, 'r') as fileopen:
name_list = [line.strip() for line in fileopen]
print (name_list)
This should be a good case for map and lambda
with open ('names.txt','r') as f :
Names = map (lambda x : x.strip(),f_in.readlines())
I stand corrected (or at least improved). List comprehensions is even more elegant
with open ('names.txt','r') as f :
Names = [name.rstrip() for name in f]
The pythonic way to read a file and put every lines in a list:
from __future__ import with_statement #for python 2.5
Names = []
with open('C:/path/txtfile.txt', 'r') as f:
lines = f.readlines()
Names.append(lines.strip())
Names = []
for line in open('names.txt','r').readlines():
Names.append(line.strip())
strip() cut spaces in before and after string...

Categories

Resources