This question already has answers here:
How do I append to a file?
(13 answers)
Closed 1 year ago.
I am trying to get the program to automatically start at the last line of a text file when I run it and make it write on the last line. My current code is as follows:
with open('textfile.txt', 'a+') as tf
last_line = tf.readlines()[-1]
tf.write(linetext + '\n')`
When I run this, it says that the list index is out of range. How do I get this to automatically skip to the last line of a text file and start writing from there?
Use the a flag while opening the file
with open('path/to/file', 'a') as outfile:
outfile.write("This is the new last line\n")
Related
This question already has answers here:
Writelines writes lines without newline, Just fills the file
(8 answers)
Closed 5 months ago.
f= open('elk.in','r')
lines = f.readlines()
for line in lines:
if line.startswith('vkloff'):
p=lines.index(line)+1
#print(lines[p])
break
lines[p] = f'{string}\n'
string=''
with open('elk.in','w') as out:
out.writelines(lines)
out.close()
Here in lines[p] if I remove \n the lines below it get removed. How does it work then?
Taking a few guesses at what your intent here is. You want to open a file, find a line starting with a given prefix, replace it with something else, then write back to the file? There's a few mistakes here if that's the case
You're trying to open a file you already have open. You should close it first.
string is not defined before you use it, assuming this is the full code.
When opening a file using with, you don't need to close it after.
With these in mind you want something like
with open('elk.in','r') as f:
lines = f.readlines()
for idx, line in enumerate(lines):
if line.startswith('vkloff'):
p = idx
break
lines[p] = f'{string}\n'
with open('elk.in','w') as out:
out.writelines(lines)
But really more information is needed about what you're trying to achieve here.
This question already has answers here:
How to append new data onto a new line
(10 answers)
Closed 9 months ago.
def password_generator():
"code to generate a password here"
file = open('/Users/benkollmar/Desktop/Projects/Passwords', 'w')
file.write(password_sentence)
Every time I call this function it writes what I want in the new file on the first line but I want to add an if statement so it only writes on the line if that line is empty. And if that line is not empty write password_sentence on the next empty line.
You should use with open() because it automatically closes the file when your done.
You can see that I used 'a' here. That means append, which means add to the end of the file. Finally, adding a \n at the end of your content forces anything appended after it later to be on a different line.
with open(passwordsFile, 'a') as file:
file.write(password_scentence + '\n')
This question already has answers here:
Prepend line to beginning of a file
(11 answers)
Closed 1 year ago.
I have build a code that does the following:
#code is supposed to access servers about 20 of them
#server details are in 'CheckFolders.ini'
# retrieve size, file numbers and number of folders information
# put all that in a file CheckFoldersResult.txt
Need to find out how can i write to CheckFoldersResult.txt so that the latest results are appended starting from the beginning of the file instead of appending at end of the existing text.
I'd read the results, insert the lines I want at the top, then overwrite the file like so:
def update_file(filepath, new_lines):
lines = []
with open(filepath, 'r') as f:
lines = f.readlines()
rev_lines = reversed(new_lines)
for line in rev_lines:
lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines)
This question already has answers here:
replacing text in a file with Python
(7 answers)
What is the best way to modify a text file in-place?
(4 answers)
Closed 1 year ago.
I followed this subject here because I want to remove the <br /> that are in my output text file.
So my code is the following one :
def file_cleaner(video_id):
with open('comments_'+video_id+'.txt', 'r') as infile, open('comments_'+video_id+'.txt', 'w') as outfile:
temp = infile.read().replace("<br />", "")
outfile.write(temp)
If I remove this function call my file has content, but after I call this function my file is empty. Where did I do something wrong ?
Opening a file in w mode truncates the file first. So there's nothing to read from the file.
Read the file first, then open it for writing.
def file_cleaner(video_id):
with open('comments_'+video_id+'.txt', 'r') as infile:
temp = infile.read().replace("<br />", "")
with open('comments_'+video_id+'.txt', 'w') as outfile:
outfile.write(temp)
This question already has answers here:
Confused by python file mode "w+" [duplicate]
(11 answers)
Closed 6 years ago.
I got nothing back from the command readline(). I am new to python and totally confused now.
my_file = open("test.txt", "w+")
my_file.write("This is a test")
print my_file.readline()
When you write to a file, you overwrite any previous contents of the file and leave the pointer at the end of the file. Any attempt to read after that will fail, since you're already at the end of the file.
To reset to the beginning of the file and read what you just wrote, use:
my_file.seek(0)
Because after you wrote content in you file. the cursor is at the end of the file. Before you use readline(), use my_file.seek(0) first, If your file content is only This is a test, you can get your want. Deep into this, please go to : https://docs.python.org/2.7/tutorial/inputoutput.html#reading-and-writing-files