Removing values in textfiles on python - python

I have the current example.txt file that contains the following names:
Names
Max
Alex
Rob
Task: How do you remove one name from the text file?

This is a very common problem, here is a quick solution. Before posting makes sure you try different code.
In this example, I use an input file and output file (2 files to do it).
infile = "file1.txt"
outfile = "file2.txt"
delete_list = ["Alex"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()

Related

Generate output file Python

As it can be seen in the code. I created two output files one for output after splitting
and second output as actual out after removing duplicate lines
How can i make only one output file. Sorry if i sound too stupid, I'm a beginner
import sys
txt = sys.argv[1]
lines_seen = set() # holds lines already seen
outfile = open("out.txt", "w")
actualout = open("output.txt", "w")
for line in open(txt, "r"):
line = line.split("?", 1)[0]
outfile.write(line+"\n")
outfile.close()
for line in open("out.txt", "r"):
if line not in lines_seen: # not a duplicate
actualout.write(line)
lines_seen.add(line)
actualout.close()
You can add the lines from the input file directly into the set. Since sets cannot have duplicates, you don't even need to check for those. Try this:
import sys
txt = sys.argv[1]
lines_seen = set() # holds lines already seen
actualout = open("output.txt", "w")
for line in open(txt, "r"):
line = line.split("?", 1)[0]
lines_seen.add(line + "\n")
for line in lines_seen:
actualout.write(line)
actualout.close()
In the first step you iterate through every line in the file, split the line on your decriminator and store it into a list. After that you iterate through the list and write it into your output file.
import sys
txt = sys.argv[1]
lines_seen = set() # holds lines already seen
actualout = open("output.txt", "w")
data = [line.split("?", 1[0] for line in open("path/to/file/here", "r")]
for line in data:
if line not in lines_seen: # not a duplicate
actualout.write(line)
lines_seen.add(line)
actualout.close()

Python split and find specific string from a text file

I have a raw data in a .txt file format and would like to convert it to .csv file format.
This is a sample data from the txt fle:
(L2-CR666 Reception Counter) L2-CR666 Reception Counter has been forced.
(L7-CR126 Handicapped Toilet) L7-CR126 Handicapped Toilet has been forced.
I would like to achieve the following result:
L2-CR666 Reception Counter, forced
L7-CR126 Handicapped Toilet, forced
I have tried the following code but was unable to achieve the stated result. Where did I went wrong?
import csv
with open('Converted Detection\\Testing 01\\2019-02-21.txt') as infile, open('Converted Detection\\Converted CSV\\log.csv', 'w') as outfile:
for line in infile:
outfile.write(infile.read().replace("(", ""))
for line in infile:
outfile.write(', '.join(infile.read().split(')')))
outfile.close()
You can try this :
with open('Converted Detection\\Testing 01\\2019-02-21.txt') as infile, open('Converted Detection\\Converted CSV\\log.csv', 'w') as outfile:
for line in infile:
# Get text inside ()
text = line[line.find("(")+1:line.find(")")]
# Remove \r\n
line = line.rstrip("\r\n")
# Get last word
forcedText = line.split(" ")[len(line.split(" "))-1]
# Remove . char
forcedText = forcedText[:len(forcedText)-1]
outfile.write(text+", "+forcedText+"\n")
outfile.close()
Best
You could use .partition() to truncate everything before ) and then simply replace the parts you do not want accordingly. Also, you do not have to close the file when using the with statement as it automatically closes it for you, and you do not have to import the csv library to save a file with the .csv extension.
The following code outputs your wanted result:
infile_path = "Converted Detection\\Testing 01\\2019-02-21.txt"
outfile_path = "Converted Detection\\Converted CSV\\log.csv"
with open(infile_path, "r") as infile, open(outfile_path, "+w") as outfile:
for line in infile:
line = line.partition(")")[2].replace(" has been forced.", ", forced").strip()
outfile.write(line + "\n")
First for loop is reading infile. No need to reread infile and second loop.
Also with block will take care of closing files.
for line in infile:
line = line.replace("(", "")
outfile.write(', '.join(line.split(')')))
I would suggest using:
lineout = ', '.join(linein.replace('(','').replace(')','').split(' has been ')
where:
linein = line.strip()

How to update a specific line in a file in python?

I am trying to create a program which can update a file.
I created a test program as I cannot figure out how to update a part of the file.
I want to make it so that if a name matches that of one in the file, it will delete the one name and its data and place the name and new data at the end.
Here is my code where I am simply trying to remove the name from the list:
lines = open("input.txt", "rt")
output = open("output.txt", "wt")
for line in lines:
if not "Ben":
output.write(line+"\n")
lines.close()
output.close()
looks like you just need to fix your condition:
lines = open("input.txt", "rt")
output = open("output.txt", "wt")
for line in lines:
if "Ben" not in line:
output.write(line+"\n")
lines.close()
output.close()
lines = open("input.txt", "rt")
output = open("output.txt", "wt")
for line in lines:
if not "Ben" in line:
output.write(line+"\n")
else:
output.write(line.replace("Ben","replace/delete Ben")+"\n")
lines.close()
output.close()

How do I remove an entire line with a specific word, from a text file?

I made a text file called contacts.txt which contains:
pot 2000
derek 45
snow 55
I want to get user input (a name) on which contact to remove, and delete the entire line containing that name. So far, this is what I've done:
# ... previous code
if int(number) == 5:
print "\n"
newdict = {}
with open('contacts.txt','r') as f:
for line in f:
if line != "\n":
splitline = line.split( )
newdict[(splitline[0])] = ",".join(splitline[1:])
print newdict
removethis = raw_input("Contact to be removed: ")
if removethis in newdict:
with open('contacts.txt','r') as f:
new = f.read()
new = new.replace(removethis, '')
with open('contacts.txt','w') as f:
f.write(new)
When I enter "pot", I come back to the text file and only "pot" is removed, the "2000" stays there. I tried
new = new.replace(removethis + '\n', '') as other forums suggested, but it didn't work.
Notes:
Everything I've read on other forums requires me to make a new file, but I don't want that; I only want one file.
I already tried 'r+' the first time I opened the file and inserted a for loop which only picks the lines that do not contain the input word, but it doesn't work either.
I saw you said this is not a duplicate, but isn't this discussion equivalent to your question?
Deleting a specific line in a file (python)
Based on the discussion in the link, I created a .txt file from your input (with the usernames you supplied) and ran the following code:
filename = 'smp.txt'
f = open(filename, "r")
lines = f.readlines()
f.close()
f = open(filename, "w")
for line in lines:
if line!="\n":
f.write(line)
f.close()
What this does is to remove the spaces between the lines.
It seems to me as if this is what you want.
How about this:
Read in all the lines from the file into a list
Write out each line
Skip the line that you want removed
Something like this:
filename = 'contacts.txt'
with open(filename, 'r') as fin:
lines = fin.readlines()
with open(filename, 'w') as fout:
for line in lines:
if removethis not in line:
fout.write(line)
If you want to be more precise about the line you remove, you could use if not line.startswith(removethis+' '), or you could put together a regular expression of some kind.

Writing a new text file in python

I'm writing code that goes over a text file counting how many words are in every line and having trouble putting the result (many lines that each consist ofa number) into a new text file.
My code:
in_file = open("our_input.txt")
out_file = open("output.txt", "w")
for line in in_file:
line = (str(line)).split()
x = (len(line))
x = str(x)
out_file.write(x)
in_file.close()
out_file.close()
But the file I'm getting has all the number together in one line.
How do I seperate them in the file I'm making?
You need to add a new line after each line :
out_file.write(x + '\n')
Also as a more pythonic way for dealing with files you can use with statement to open the files which will close the files at the end of the block.
And instead of multiple assignment and converting the length to string you can use str.format() method to do all of this jobs in one line:
with open("our_input.txt") as in_file,open("output.txt", "w") as out_file:
for line in in_file:
out_file.write('{}\n'.format(len(line.split())))
Add newline in the file while writing
in_file = open("our_input.txt")
out_file =open("output.txt", "w")
for line in in_file:
line= (str(line)).split()
x=(len(line))
x=str(x)
out_file.write(x)
#Write newline
out_file.write('\n')
in_file.close()
As the previous answers have pointed out, your need to write a newline to separate the ouput.
Here is yet another way to write the code
with open("our_input.txt") as in_file, open("output.txt", "w") as out_file:
res = map(lambda line: len(line.split()), in_file)
for r in res:
out_file.write('%d\n' % r)

Categories

Resources