How can append a string to every number on a text file? - python

I have a phone number list,each on a new line and I want to append a string “#ctest.com” to the end of every new line.
with open(“demofile.txt”, “r”) as f1:
Lines = f1.readlines()
For x in Lines:
f= open(“demofile.txt”, “a”)
f.writelines([“#vtest.com”])
f.close()
y = open(“demofile.txt”, “r”)
Print(Y.read())
I was expecting each line to print as below
7163737373#vtest.com
7156373737#vtest.com
For all the files on new lines.
But I got this
7163737373
7156373737#vtest.com,vtest.com

You're not appending to each line, you're just appending #vtestcom to the end of the file each time through the loop.
You need to reopen the file in write mode, not append mode, and write each x from the original readlines().
with open("demofile.txt", "r") as f1:
lines = f1.readlines()
with open("demofile.txt", "w") as f:
for line in lines:
f.write(f'{line.strip()}#ctest.com\n')
with open("demofile.txt", "r") as y:
print(y.read())
FYI, this is much easier to do in bash:
sed -i 's/$/#vtest.com' demofile.txt

Related

How would I write separate words to a file, with words between them?

I am trying to write words from words.txt to newfile.txt using python3, with a format like this:
words.txt:
Hello
I
am
a
file
and I want the word Morning added between each new word in words.txt, inside a new file called newfile.txt.
so newfile.txt should look like this:
Hello
Morning
I
Morning
Am
Morning
A
Morning
File
Does anyone know how to do this?
Sorry about the bad phrasing,
Gomenburu
To avoid blowing main memory for a large file, you'd want to insert the extra strings as you go. It's not hard, just a little tricky to ensure they only go between existing lines, not at the beginning or end:
# Open both files
with open('words.txt') as inf, open('newfile.txt', 'w') as outf:
outf.write(next(inf)) # Copy over first line without preceding "Morning"
for line in inf: # Lazily pull remaining lines from infile one by one
outf.write("Morning\n") # Write the in-between "Morning" before each new line
outf.write(line) # Write pre-existing line
with open("words.txt", "r") as words_file, open("newfile.txt", "w") as new_words_file:
new_words_file.write("\n".join([f"{word}\nMorning" for word in words_file.read().split("\n")]))
with open('words.txt') as f:
lines = f.readlines()
for i in range(len(lines)):
a = lines[i] + 'Morning' + '\n'
with open('newfile.txt','a') as file:
file.write(a)
file.close()
This should do it!
I would start with this:
f1 = open( 'words.txt')
f2 = open( 'newfile.txt')
lines = f1.readlines()
for line in lines:
f2.write( line + "Morning\n")
f2.close()

How to get first letter of each line in python?

here is what I got txt and open
txt file looks like
f = open('data.txt', 'r')
print(f.read())
the show['Cat\n','Dog\n','Cat\n','Dog\n'........]
output
But I would like to get this
['C\n','D\n','C\n','D\n'........]
First you'll want to open the file in read mode (r flag in open), then you can iterate through the file object with a for loop to read each line one at a time. Lastly, you want to access the first element of each line at index 0 to get the first letter.
first_letters = []
with open('data.txt', 'r') as f:
for line in f:
first_letters.append(line[0])
print(first_letters)
If you want to have the newline character still present in the string you can modify line 5 from above to:
first_letters.append(line[0] + '\n')
f = open("data.txt", "r")
for x in f:
print(x[0])
f.close()

Python removing line from text file is removing everything

I'm trying to remove one line which matches a variable. But instead it is wiping the file clean.
a_file = open("./Variables/TxtFile.txt", "r")
lines = a_file.readlines()
a_file.close()
new_file = open("./Variables/TxtFile.txt", "w")
for line in lines:
if line.strip("\n") == VariableStore:
new_file.write(line)
new_file.close()
The goal would be to remove the line that matches VariableStore rather than wiping the entire text file
In regard to my comment to your original post.
You only write to the file if you match the line you want to remove and then also close the file.
This seems not to be what you want.
You might want to change the if condition to be executed in cases that do not match your line you want to remove, i.e., to if not line.strip("\n") == VariableStore: and close the file after your loop, i.e., on the same level as your for loop.
Try the following, which incorporates these suggestions:
a_file = open("./Variables/TxtFile.txt", "r")
lines = a_file.readlines()
a_file.close()
new_file = open("./Variables/TxtFile.txt", "w")
for line in lines:
if not line.strip("\n") == VariableStore:
new_file.write(line)
new_file.close()
If your aim is to filter out the line matching VariableStore, do this:
with open("./Variables/TxtFile.txt", "r") as a_file:
lines = a_file.readlines()
with open("./Variables/TxtFile.txt", "w") as new_file:
for line in lines:
if line.strip("\n") != VariableStore:
continue # Skip the VariableStore line
new_file.write(line) # Write other lines
When you use with statements, you don't need to manually close the file.
You just need to close the file later on, when you are done parsing all the lines.
Also, you need to write the lines that don't match, not the one's that do.
Note the changes below:
# Read file
a_file = open("./Variables/TxtFile.txt", "r")
lines = a_file.readlines()
a_file.close()
# Write file
new_file = open("./Variables/TxtFile.txt", "w")
for line in lines:
if line.strip("\n") == VariableStore:
# Don't write this line
pass
else:
new_file.write(line)
new_file.close()
Let us assume that your text file TxtFile.txt contains this text
Hello
World
I'm
Python
Developer
And you have a variable var contains the string World which we want to remove from the text file.
Here is a python code does the job in few lines
var='World' # a string to remove
with open("TxtFile.txt","r+") as f:
lines = f.readlines()
lines = [line for line in lines if line.strip()!=var]
f.seek(0)
f.writelines(lines)
f.truncate()
The text file after running this code..
Hello
I'm
Python
Developer
The problem is that you're opening the file with write mode instead of append mode. Replace
new_file = open("./Variables/TxtFile.txt", "w")
with
new_file = open("./Variables/TxtFile.txt", "a")
and you'll append the data instead of overwriting it.
Also, it's generally recommended to open files using the 'with' statement, since that automatically closes the file for you.
with open("./Variables/TxtFile.txt", "a") as text_file:
...

How to modify a line in a file using Python

I am trying to do what for many will be a very straight forward thing but for me is just infuriatingly difficult.
I am trying search for a line in a file that contains certain words or phrases and modify that line...that's it.
I have been through the forum and suggested similar questions and have found many hints but none do just quite what I want or are beyond my current ability to grasp.
This is the test file:
# 1st_word 2nd_word
# 3rd_word 4th_word
And this is my script so far:
############################################################
file = 'C:\lpthw\\text'
f1 = open(file, "r+")
f2 = open(file, "r+")
############################################################
def wrline():
lines = f1.readlines()
for line in lines:
if "1st_word" in line and "2nd_word" in line:
#f2.write(line.replace('#\t', '\t'))
f2.write((line.replace('#\t', '\t')).rstrip())
f1.seek(0)
wrline()
My problem is that the below inserts a \n after the line every time and adds a blank line to the file.
f2.write(line.replace('#\t', '\t'))
The file becomes:
1st_word 2nd_word
# 3rd_word 4th_word
An extra blank line between the lines of text.
If I use the following:
f2.write((line.replace('#\t', '\t')).rstrip())
I get this:
1st_word 2nd_wordd
# 3rd_word 4th_word
No new blank line inserted but and extra "d" at the end instead.
What am I doing wrong?
Thanks
Your blank line is coming from the original blank line in the file. Writing a line with nothing in it writes a newline to the file. Instead of not putting anything into the written line, you have to completely skip the iteration, so it does not write that newline. Here's what I suggest:
def wrline():
lines = open('file.txt', 'r').readlines()
f2 = open('file.txt', 'w')
for line in lines:
if '1st_word' in line and '2nd_word' in line:
f2.write((line.replace('# ', ' ')).rstrip('\n'))
else:
if line != '\n':
f2.write(line)
f2.close()
I would keep read and write operations separate.
#read
with open(file, 'r') as f:
lines = f.readlines()
#parse, change and write back
with open(file, 'w') as f:
for line in lines:
if line.startswith('#\t'):
line = line[1:]
f.write(line)
You have not closed the files and there is no need for the \t
Also get rid of the rstrip()
Read in the file, replace the data and write it back.. open and close each time.
fn = 'example.txt'
new_data = []
# Read in the file
with open(fn, 'r+') as file:
filedata = file.readlines()
# Replace the target string
for line in filedata:
if "1st_word" in line and "2nd_word" in line:
line = line.replace('#', '')
new_data.append(line)
# Write the file out again
with open(fn, 'w+') as file:
for line in new_data:
file.write(line)

How to remove line that contain a certain string in python

I have a text file that looks like this
Big:house
small:door
Big:car
Small:chair
Big:plane
How to I remove the lines that contain the word "big" so it may look like this, I dont want to create a new file all together though
small:door
small:chair
Here was my attempt
with open('QWAS.txt','r') as oldfile:
for line in oldfile:
if bad_words in line:
newfile.write(line)
This is what we can do:
Read data to string (remove rows that start with 'big')
Go to the start of file (seek)
Write the string
Truncate (remove overflow)
And now to the code, open it in read and write mode:
with open('QWAS.txt','r+') as f:
data = ''.join([i for i in f if not i.lower().startswith('big')]) #1
f.seek(0) #2
f.write(data) #3
f.truncate() #4
Try this:
newfile = r'output.txt'
oldfile = r'input.txt'
with open(newfile, 'w') as outfile, open(oldfile, 'r') as infile:
for line in infile:
if if line[:5].lower() == 'small':
outfile.write(line)
#output
small:door
Small:chair
Of course, this assumes you want to eliminate rows where small or Small is to the left of the colon. Additionally, you will have a new file output, as I don't think you really want to update your input file.
You can try using regular expressions
import re
oldfile = open('QWAS.txt','r')
newfile = open('newfile.txt','w')
for line in oldfile:
if re.search('[Ss]mall',line):
newfile.write(line)
oldfile.close()
newfile.close()
Which gives the output file "newfile.txt"
small:door
Small:chair
If you just take every line that doesn't have small and write it to a new file "newfile2.txt"
import re
oldfile = open('QWAS.txt','r')
newfile = open('newfile.txt','w')
newfile2 = open('newfile2.txt','w')
for line in oldfile:
if re.search('[Ss]mall',line):
newfile.write(line)
else:
newfile2.write(line)
oldfile.close()
newfile.close()
newfile2.close()

Categories