Adding data to end of existing file python - python

So my code looks like this ....
but I want to add data always to the end of the document
how would I do this
try:
f = open("file.txt", "w")
try:
f.write('blah') # Write a string to a file
f.writelines(lines) # Write a sequence of strings to a file
finally:
f.close()
except IOError:
pass

Open the file using 'a' (append) instead of 'w' (write, truncate)
Besides that, you can do the following isntead of the try..finally block:
with open('file.txt', 'a') as f:
f.write('blah')
f.writelines(lines)
The with block automatically takes care about closing the file at the end of the block.

open the file with "a" instead of "w"

Related

Create a filename using the value of a Variable

I'm trying to create a filename of a variable and it's more difficult than i realised!
I want to use the value of the TESTNAME variable as the name of the new file.
import re
with open('output.csv', 'r') as rf:
body = rf.read()
for line in body:
newbody = body.rsplit("'")[0]
print(newbody)
SYMNAME = newbody
with open('TEST.txt', 'w') as wf:
wf.close
If i print(TESTNAME), the value is HISTORY, but if i add it to the wf, i get this error:
[Errno 22] Invalid argument: 'HISTORY\n'
I'd like the new file to be called HISTORY.txt via the variable..
The problem is that there is a newline in your filename. You can use TESTNAME.strip() as the filename instead to get rid of the trailing newline
You can open and write to a file with
with open(TESTNAME+'.txt') as wf:
wf.write("some content in your new file\n")
wf.close won't do anything, to close a file you need to call wf.close(), the parenthesis here is important. Also , you don't actually need to call wf.close(), since using with ... will automatically close() the file.

How opened file cannot be rewind by seek(0) after using with open() in python

While I was trying to print file content line by line in python, I cann't rewind the opened file by f.seek(0) to print the content if the file was opened by with open("file_name") as f:
but, I can do this if I use open("file_name") as f:
then f.seek(0)
Following is my code
with open("130.txt", "r") as f: #f is a FILE object
print (f.read()) #so f has method: read(), and f.read() will contain the newline each time
f.seek(0) #This will Error!
with open("130.txt", "r") as f: #Have to open it again, and I'm aware the indentation should change
for line in f:
print (line, end="")
f = open("130.txt", "r")
f.seek(0)
for line in f:
print(line, end="")
f.seek(0) #This time OK!
for line in f:
print(line, end="")
I am a python beginner, can anybody tell me why?
The first f.seek(0) will throw an error because
with open("130.txt", "r") as f:
print (f.read())
will close the file at the end of the block (once the file has be printed out)
You'll need to do something like:
with open("130.txt", "r") as f:
print (f.read())
# in with block
f.seek(0)
The purpose of with is to clean up the resource when the block ends, which in this case would include closing the file handle.
You should be able to .seek within the with block like this, though:
with open('130.txt','r') as f:
print (f.read())
f.seek(0)
for line in f:
print (line,end='')
From your comment, with in this case is syntactic sugar for something like this:
f = open(...)
try:
# use f
finally:
f.close()
# f is still in scope, but the file handle it references has been closed

Attempt to use the open() function failing

I'm trying to learn to manipulate files on python, but I can't get the open function to work. I have made a .txt file called foo that holds the content "hello world!" in my user directory (/home/yonatan) and typed this line into the shell:
open('/home/yonatan/foo.txt')
What i get in return is:
<_io.TextIOWrapper name='/home/yonatan/foo.txt' mode='r' encoding='UTF-8'>
I get what that means, but why don't I get the content?
open() returns a file object.
You then need to use read() to read the whole file
f = open('/home/yonatan/foo.txt', 'r')
contents = f.read()
Or you can use readline() to read just one line
line = f.readline()
and don't forget to close the file at the end
f.close()
An example iterating through the lines of the file (using with which ensures file.close() gets called on the end of it's lexical scope):
file_path = '/home/yonatan/foo.txt'
with open(file_path) as file:
for line in file:
print line
A great resource on I/O and file handling operations.
You haven't specified the mode you want to open it in.
Try:
f = open("home/yonatan/foo.txt", "r")
print(f.read())

How can I tell python to edit another python file?

Right now, I have file.py and it prints the word "Hello" into text.txt.
f = open("text.txt")
f.write("Hello")
f.close()
I want to do the same thing, but I want to print the word "Hello" into a Python file. Say I wanted to do something like this:
f = open("list.py")
f.write("a = 1")
f.close
When I opened the file list.py, would it have a variable a with a value 1? How would I go about doing this?
If you want to append a new line to the end of a file
with open("file.py", "a") as f:
f.write("\na = 1")
If you want to write a line to the beginning of a file try creating a new one
with open("file.py") as f:
lines = f.readlines()
with open("file.py", "w") as f:
lines.insert(0, "a = 1")
f.write("\n".join(lines))
with open("list.py","a") as f:
f.write("a=1")
This is simple as you see. You have to open that file in write and read mode (a). Also with open() method is safier and more clear.
Example:
with open("list.py","a") as f:
f.write("a=1")
f.write("\nprint(a+1)")
list.py
a=1
print(a+1)
Output from list.py:
>>>
2
>>>
As you see, there is a variable in list.py called a equal to 1.
I would recommend you specify opening mode, when you are opening a file for reading, writing, etc. For example:
for reading:
with open('afile.txt', 'r') as f: # 'r' is a reading mode
text = f.read()
for writing:
with open('afile.txt', 'w') as f: # 'w' is a writing mode
f.write("Some text")
If you are opening a file with 'w' (writing) mode, old file content will be removed. To avoid that appending mode exists:
with open('afile.txt', 'a') as f: # 'a' as an appending mode
f.write("additional text")
For more information, please, read documentation.

Python: Writing to a File

I've been having trouble with this for a while. How do I open a file in python and continue writing to it but not overwriting what I had written before?
For instance:
The code below will write 'output is OK'.
Then the next few lines will overwrite it and it will just be 'DONE'
But I want both
'output is OK'
'DONE'
in the file
f = open('out.log', 'w+')
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
f.flush()
f.close()
# some other work
f = open('out.log', 'w+')
f.write('done\n')
f.flush()
f.close()
I want to be able to freely open and write to it in intervals. Close it. Then repeat the process over and over.
Thanks for any help :D
Open the file in append mode. It will be created if it does not exist and it will be opened at its end for further writing if it does exist:
with open('out.log', 'a') as f:
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
# some other work
with open('out.log', 'a') as f:
f.write('done\n')
Just pass 'a' as argument when you open the file to append content in it. See the doc
f = open('out.log', 'a')
You need to open the file in append mode the second time:
f = open('out.log', 'a')
because every time you open the file in the write mode, the contents of the file get wiped out.
After the first writting, you need to use f = open('out.log', 'a') to append the text to the content of your file.
with open("test.txt", "a") as myfile:
myfile.write("appended text")

Categories

Resources