how do i delete a line that contains a certain string? - python

What I am trying to do here is :
1.read lines from a text file.
2.find lines that contain certain string.
3.delete that line and write the result in a new text file.
For instance, if I have a text like this:
Starting text
How are you?
Nice to meet you
That meat is rare
Shake your body
And if my certain string is 'are'
I want the output as:
Starting text
Nice to meet you
Shake your body
I don't want something like:
Starting text
Nice to meet you
Shake your body
I was trying something like this:
opentxt = open.('original.txt','w')
readtxt = opentxt.read()
result = readtxt.line.replace('are', '')
newtxt = open.('revised.txt','w')
newtxt.write(result)
newtxt.close()
But it don't seem to work...
Any suggestions? Any help would be great!
Thanks in advance.

Same as always. Open source file, open destination file, only copy lines that you want from the source file into the destination file, close both files, rename destination file to source file.

with open('data.txt') as f,open('out.txt') as f2:
for x in f:
if 'are' not in x:
f2.write(x.strip()+'\n') #strip the line first and then add a '\n',
#so now you'll not get a empty line between two lines

Related

Can not configure output in quoted text

Sir need some help.
I think it's an easy task but I cannot configure it.
I want to compare two text files & output the differences in quoted text.
I tried this post-https://stackoverflow.com/a/28216365/12031112 & it's working fine, but I cannot
get output in quoted text.
def compare(File1,File2):
with open(File1,'r') as f:
d=set(f.readlines())
with open(File2,'r') as f:
e=set(f.readlines())
open('file3.txt','w').close() #Create the file
with open('file3.txt','a') as f:
for line in list(d-e):
f.write(line)
File1 = 'Updatedfile1.txt'
File2 = 'Rawfile2.txt'
compare(File1,File2)
for example: In text file it was without a quote & each line ie
boofx.com
uooos.com
jiooq.com
But want output like below in file3.txt:
"boofx.com",
"uooos.com",
"jiooq.com",
"zcrcd.com",
"jeoce.com",
"xcoxc.com",
"cdfaq.com",
& in the last line without a comma(,).
Any solution will be highly appreciated.

How to handle typos when cleansing a text file?

I'm trying to clean a text file in python. I noticed the text file I'm reading in has several typos (ie. chevroelt instead of chevrolet). I have a specific list of typos that I'd like to address. How would I approach making these edits as I read in an input file to a new (clean) output file? Below is the code I have written to read in the original text file and output to a new (clean) file. I appreciate any help in advance!
def _clean_data(self):
ifname = AutoMPGData.DATA_FILE_ORIG
ofname = AutoMPGData.DATA_FILE_CLEAN
with open(ifname, 'r') as ifile:
with open(ofname, 'w') as ofile:
for line in ifile:
ofile.write(line.expandtabs())
If you have a list of specific issues you'd like to address, I would create a map (tuple?) of all words with typo as key and the correct spelling as value, then something like this (pseudocode):
for each word in file:
if word is in keys:
word = key.value

Read text from a .txt file and insert a string using python

Okay so long story short I want to read a .txt file into my program and then insert a string at a specific point in the text. The output would look something along the lines of this:
"text from file {string} more text from file"
This is the relevant code I'm currently working with:
with open(r"act 1 text\act_1_scene_1_talk.txt","r+") as scene_1_talk_file:
scene_1_talk = scene_1_talk_file.read()
print(input("Press enter to continue. "))
print(f"{scene_1_talk}")
I suppose I could just cut the text file in half and then put the string in between it, but I would prefer to keep the file in one body. I can provide additional code segments to help clarify anything.
Let's say you want to put your {string} at, like, middle of the text file. Then you can
with open('note.txt', "r") as f:
f_read = f.read()
middle_position = int(len(f_read) / 2) - 1 //minus one because array starts from zero
//strings are immutable, so we need another variable to store the new string
result = f_read[:middle_position] + "{string}" + f_read[middle_position:]
print(result)

Python putting all words on same line

I am trying to remove some words (located on a text file) on another text file. Although my code seems to work, I noticed that it stopped removing words at a certain point in the text file. I then checked the text file, and noticed that Python is writing all the words on the same line, and this line has a limit of characters to it, resulting in the process stopping. How can I circumvent that?
Here is my code:
# text file list to array
with open('function_words.txt') as functionFile:
functionWords = [word for line in functionFile for word in line.split()]
# delete the word on the text file if it matches one of the array
with open("results.txt", "r+") as newfile:
newfile.write(' '.join(i for i in toPrint.read().split() if i not in functionWords))
Thanks in advance and please let me know if you need more details.
you would need to put the "\n" after you join the string if you want each line separate in the new file. Note the + "\n" below.
with open("results.txt", "r+") as newfile:
newfile.write(' '.join(i for i in toPrint.read().split() if i not in functionWords)+ "\n")
alt. you could create a list of the lines you want to write and write newFile using the writelines() methods. Something like:
newFile.writelines(my_list_of_lines_to_write)

How to import and print seperate txt file in spyder?

I am trying to import several text files into my Spyder file, which I want to add to a list later on.
why does
test1 = open("test1.txt")
result in test1 as "TextIOWrapper"? How would I bring the content over into the python file?
Thanks in advance
You need to read the lines into your list after opening it. For example, the code should be:
with open('test1.txt') as f:
test1= f.readlines()
The above code will read the contents of your text file into the list test1. However, if the data in your text file is separated over multiple lines, the escape char '\n' will be included in your list.
To avoid this, use the below refined code:
test1= [line.rstrip('\n') for line in open('test1.txt')]

Categories