How to update a specific line in a file in python? - 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()

Related

How to add empty lines between lines in text.txt document?

The purpose of the code is to add an empty line between lines in text.txt document and write some words in those empty lines.
I tried looping through every line but the file should be in read mode only;
iushnaufihsnuesa
fsuhadnfuisgadnfuigasdf
asfhasndfusaugdf
suhdfnciusgenfuigsaueifcas
This is a sample of text.txt document
how can i implement this on this txt?
f = open("text.txt", 'w+')
for x in f:
f.write("\n Words between spacing")
f.close()
First i tried directly to just make a new line between each line and add couple of stuuf
I also thought of first making empty lines between each line and then add some words in the empty spaces but I didn't figure this out
Ok, for files in the region of 200 lines long you can store the whole file as a list of strings and add lines when re-writing the file:
with open("text.txt", 'r') as f:
data = [line for line in f]
with open("text.txt", 'w') as f:
for line in data:
f.write(line)
f.write("Words between spacing\n")
You can divide this operation in three steps.
In the first one, you read all the lines from the file into a list[str] using f.readlines():
with open("text.txt", "r") as f: # using "read" mode
lines = f.readlines()
Second is to join these lines inside the list using the "".join(...) function.
lines = "My line between the lines\n".join(lines)
On third step, write it down to the file:
with open("text.txt", "w") as f: # using "write" mode
f.write(lines)
Also, you can use f.read() in conjunction with text.replace("\n", ...):
with open("text.txt", "r") as f:
full_text = f.read()
full_text = full_text.replace("\n", "\nMy desirable text between the lines\n")
with open("text.txt", "w") as f:
f.write(full_text)
Initial text:
iushnaufihsnuesa
fsuhadnfuisgadnfuigasdf
asfhasndfusaugdf
suhdfnciusgenfuigsaueifcas
Final text:
iushnaufihsnuesa
My desirable text between the lines
fsuhadnfuisgadnfuigasdf
My desirable text between the lines
asfhasndfusaugdf
My desirable text between the lines
suhdfnciusgenfuigsaueifcas

Printing the first paragraph from infile to outfile

I have one file containing a speech, and have an empty output file. I am trying to print the first paragraph of the speech (read infile) and print it out to the outfile using if/else statement.
the program isn't bugging but its not outputting to my outfile.
file = open("/Users/newuser/Desktop/MLKspeech.txt", "r")
file2 = open("/Users/newuser/Desktop/mlkparagraph.txt", "w")
content = file.read()
for j in content:
if (j == ""):
continue
elif (j == "\n"):
file2.write(content)
else:
break
Assuming paragraphs are separated by an empty line, you can iterate on the file line-by-line and write them to the new file, until an empty line is reached. An empty line can be discovered with str.isspace():
with open("MLKspeech.txt") as in_file, open("mlkparagraph.txt", 'w') as out_file:
for line in in_file:
if line.isspace():
break
out_file.write(line)
Assuming your paragraphs are separated with the '\t' character, you could try this:
with open('file1.txt', mode='rt') as file:
breakpoint = file.read().find('\t')
file.seek[0]
with open('file2.txt', mode='wt') as file2:
file2.write(file.read()[:breakpoint])
The goal is to capture the first few lines of your input file until you read an empty line (where there is either nothing or only a newline character). One way of doing that is to iterate through each line in the text with f.readlines() and store only the lines that you need in a list, breaking when you read an empty line:
content = []
with open('infile.txt') as f:
for line in f.readlines():
if line in ('', '\n'):
break
content.append(line)
You can then write each line to your output file:
with open('outfile.txt', 'w') as f:
for line in content:
f.write(line)

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()

Removing values in textfiles on 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()

make list from text file and compare the lists

The full.txt contains:
www.example.com/a.jpg
www.example.com/b.jpg
www.example.com/k.jpg
www.example.com/n.jpg
www.example.com/x.jpg
The partial.txt contains:
a.jpg
k.jpg
Why the following code does not provide the desired result?
with open ('full.txt', 'r') as infile:
lines_full=[line for line in infile]
with open ('partial.txt', 'r') as infile:
lines_partial=[line for line in infile]
with open ('remaining.txt', 'w') as outfile:
for element in lines_full:
if element[16:21] not in lines_partial: #element[16:21] means like a.jpg
outfile.write (element)
The desired remaining.txt should have those elements of full.txt that are not in partial.txt exactly as follows:
www.example.com/b.jpg
www.example.com/n.jpg
www.example.com/x.jpg
you can use os.path library:
from os import path
with open ('full.txt', 'r') as f:
lines_full = f.read().splitlines()
with open ('partial.txt', 'r') as f:
lines_partial = set(f.read().splitlines()) # create set for faster checking
lines_new = [x + '\n' for x in lines_full if path.split(x)[1] not in lines_partial]
with open('remaining.txt', 'w') as f:
f.writelines(lines_new)
This code will include the newline character at the end of each line, which means it will never match "a.jpg" or "k.jpg" precisely.
with open ('partial.txt', 'r') as infile:
lines_partial=[line for line in infile]
Change it to
with open ('partial.txt', 'r') as infile:
lines_partial=[line[:-1] for line in infile]
to get rid of the newline characters (line[:-1] means "without the last character of the line")

Categories

Resources