Python move cursor to end of .txt lines - python

I need to write() text at the end of every line in a text file. How do I point the cursor to the end of a specific line.
Note: seek(0,2) will put me at the end of the file, but I need the end of each line.
Appreciate the help guys - I've combined your solutions to achieve what I need:
AllLines = [ (str.rstrip('\n') + 'Val2' + "\n" ) for str in AllLines ]
I can then write AllLines to a new output file.

You need to do this in two steps. Since it's safer to create a new file, you could:
with open("input.txt") as infile, open("output.txt", "w") as outfile:
for line in infile:
outfile.write(line.rstrip("\n") + "added text\n")

new_lines = []
with open("my_file") as f:
new_lines = [line.strip("\n")+"some_ending_stuff" for line in f]
with open("my_file","w") as f:
f.write("\n".join(new_lines))
something like that should work

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

Deleting line from file by containing a specific string is not working in python

I'm trying to delete each line which contains "annote = {" but my code is not working.
I have a file stored in a variable myFile and I want to go through every line of this file and delete every line which contains the string annote.
this is basically my code:
print(myFile.read()) //prints myFile
myFile.seek(0)
for lines in myFile:
if b"annote = {" in lines:
lines = lines.replace(b'.', b'')
myFile.seek(0)
print(myFile.read()) //this prints the exact same as the print method above so annote lines
//haven't been removed from this file
I have no idea why annote lines doesn't get removed. There is probably anything wrong with the replace method because it always is inside the if request but nothing happens with annote lines. I've also tried lines.replace(b'.', b'') instead of lines = lines.replace(b'.', b'') but nothing happened.
Hope anyone can help me with this problem
This will do it for you.
f.readlines() returns a list of text lines
Then you check for the lines that do not contain the things you do not want
Then you write them to a separate new file.
f2 = open('newtextfile.txt', 'w')
with open('text_remove_line.txt', 'r') as f:
for line in f.readlines():
if 'annote = {' not in line:
f2.write(line)
f2.close()
This should work:
with open('input.txt') as fin :
lines = fin.read().split('\n') # read the text, split into the lines
with open('output.txt', 'w') as fout :
# write out only the lines that does not contain the text 'annote = {'
fout.write( '\n'.join( [i for i in lines if i.find('annote = {') == -1] ))

Adding a new string to the end of a specific line in a text file

I'm new to python hence I am unable to implement the solutions I've found online in order to fix my problem.
I am trying to add a specific string to the end of a specific line to a textfile. As I understand text commands, I must overwrite the file if I don't want to append to the end of it. So, my solution is as follows:
ans = 'test'
numdef = ['H',2]
f = open(textfile, 'r')
lines = f.readlines()
f.close()
f = open(textfile, 'w')
f.write('')
f.close()
f = open(textfile, 'a')
for line in lines:
if int(line[0]) == numdef[1]:
if str(line[2]) == numdef[0]:
k = ans+ line
f.write(k)
else:
f.write(line)
Basically, I am trying to add variable ans to the end of a specific line, the line which appears in my list numdef. So, for example, for
2 H: 4,0 : Where to search for information : google
I want
2 H: 4,0 : Where to search for information : google test
I have also tried using line.insert() but to no avail.
I understand using the 'a' function of the open command is not so relevant and helpful here, but I am out of ideas. Would love tips with this code, or if maybe I should scrap it and rethink the whole thing.
Thank you for your time and advice!
When you use the method
lines = f.readlines()
Python automatically adds "\n" to the end of each line.
Try instead of :
k = line+ans
The following:
k = line.rstrip('\n') + ans
Good luck!
Try this. You don't have an else case if it meets the first requirement but not the other.
ans = 'test'
numdef = ['H',2]
f = open(textfile, 'r')
lines = f.readlines()
f.close()
f = open(textfile, 'w')
f.write('')
f.close()
f = open(textfile, 'a')
for line in lines:
if int(line[0]) == numdef[1] and str(line[2]) == numdef[0]:
k = line.replace('\n','')+ans
f.write(k)
else:
f.write(line)
f.close()
Better way:
#initialize variables
ans = 'test'
numdef = ['H',2]
#open file in read mode, add lines into lines
with open(textfile, 'r') as f:
lines=f.readlines()
#open file in write mode, override everything
with open(textfile, 'w') as f:
#in the list comprehension, loop through each line in lines, if both of the conditions are true, then take the line, remove all newlines, and add ans. Otherwise, remove all the newlines and don't add anything. Then combine the list into a string with newlines as separators ('\n'.join), and write this string to the file.
f.write('\n'.join([line.replace('\n','')+ans if int(line[0]) == numdef[1] and str(line[2]) == numdef[0] else line.replace('\n','') for line in lines]))

What's wrong with my code to read and replace python text file line by line? [duplicate]

This question already has answers here:
Search and replace a line in a file in Python
(13 answers)
Closed 5 years ago.
I have a text file. I would like to use python v3.6 to read the text file line by line, append each line with a sub-string and replace the existing line with the appended string line by line.
To be clearer, here is the original text file;
1,2,3
4,5,6
The desired output text file should look like this;
appended_text,1,2,3
appended_text,4,5,6
This is how my code looks like;
with open(filename, 'r+') as myfile:
for line in myfile:
newline = "appended_text" + "," + line
myfile.write(newline)
I did not get what I want. What I got instead was a huge line of text appended at the end of the file. How should the code be modified? Is there a better way to implement what I want?
There's no such thing as "replacing an existing line" in a file. For what you want to do, you have to write a new file with the modified content and then replace the old file with the new one. Example code:
with open("old.file") as old, open("new.file", "w") as new:
for line in old:
line = modify(line.lstrip())
new.write(line + "\n")
os.rename("new.file", "old.file")
You cannot, in general, modify a file in place like this. Instead, write a copy to a new file, then replace the original with the new one.
with open(filename, 'r') as myfile:
with open("copy", 'w') as newfile:
for line in myfile:
newline = "appended_text" + "," + line
newfile.write(newline)
os.rename("copy", filename)
If you want to write it to the same file:
f = open(filename, 'r')
lines = f.readlines()
f.close()
lines = ['appended_text, ' + l for l in lines]
f = open(filename, 'w')
f.writelines(lines)
f.close()
Here is what I would do:
with open(filename, 'r+') as f:
lines = []
for line in f:
lines.append("appended_text" + "," + line)
f.seek(0)
for line in lines:
f.write(line)
For example:
sample.txt before:
hello
there
world
code:
fp = r"C:\Users\Me\Desktop\sample.txt"
with open(fp, 'r+') as f:
lines = []
for line in f:
lines.append("something," + line)
lines.append(line.strip() + ",something\n")
f.seek(0)
for line in lines:
f.write(line)
sample.txt after:
something,hello
hello,something
something,there
there,something
something,world
world,something
A couple of notes:
This assumes you are going to append to the front of each line. Thus the newline ('\n') is kept with the original content of each line. If you are appending to the end, I would change to: lines.append(line.strip() + "," + "appended_text").
You can probably combine "appended_text" and the "," to "appended_text,". Unless "appended_text" is a varable like appended_text = "something".
Though contextually correct as a solution to your question; I'd look to writing a new file with the changes desired and replacing the old one with the new one as recommend in other answers.
I believe to get what you want you need to put myfile.readlines() before your for loop.

Python read file by line and write into a different file

SO basically what I am trying to do is that I am trying to make it so I can read a file line by line, and then have a certain text added after the text displayed
For Ex.
Code:
file = open("testlist.txt",'w')
file2 = open("testerlist.txt",'r+')
//This gives me a syntax error obviously.
file.write1("" + file + "" + file2 + "")
Textlist
In my testlist.txt it lists as:
os
Testerlist
In my testerlist.txt it lists as:
010101
I am trying to copy one text from one file and read another file and add it to the beginning of a new file for ex.[accounts.txt].
My End Result
For my end result I am trying to have it be like:
os010101
(btw I have all the correct code, its just that I am using this as an example so if I am missing any values its just because I was to lazy to add it.)
You can use file.read() to read the contents of a file. Then just concatenate the data from two files and write to the output file:
with open("testlist.txt") as f1, open("testerlist.txt") as f2, \
open("accounts.txt", "w") as f3:
f3.write(f1.read().strip() + f2.read().strip())
Note that 'mode' is not required when opening files for reading.
If you need to write the lines in particular order, you could use file.readlines() to read the lines into a list and file.writelines() to write multiple lines to the output file, e.g.:
with open("testlist.txt") as f1, open("testerlist.txt") as f2, \
open("accounts.txt", "w") as f3:
f1_lines = f1.readlines()
f3.write(f1_lines[0].strip())
f3.write(f2.read().strip())
f3.writelines(f1_lines[1:])
Try with something like this:
with open('testlist.txt', 'r') as f:
input1 = f.read()
with open('testerlist.txt', 'r') as f:
input2 = f.read()
output = input1+input2
with open("accounts.txt", "a") as myfile:
myfile.write(output)

Categories