This question already has answers here:
How do I append to a file?
(13 answers)
Closed 5 years ago.
I have a function which prints messages. then I want to save this messages into a file. But when I use .write(function parameter) it only write last message inside my file
writing_in_log = True
def print_and_log(message):
if write_in_log is True:
logFile = open("log", "w+")
logFile.write(message)
logFile.close()
I suppose you are not using the 'a' parameter when opening the file:
with open('file.txt', 'a') as file:
file.write('function parameter')
You probably open the file for each writing with open(yourfile, 'w') which will erase any content from the file before you write to it. If you want to append to your file, use open(yourfile, 'a').
In case this is not the error we need more information about what you are doing, i.e. the relevant parts of the code.
Related
This question already has answers here:
Understanding the Python 'with' statement
(5 answers)
Closed 4 years ago.
I am using python 2.x and I am going through company code, I found code that looks like:
filename = open('text.json', 'r')
# doSomething()
filename.close()
I am used to reading a file like so:
with open('text.json', 'r') as filename
# doSomething()
Can anyone explain what the difference is?
The second one is usually used with a context manager, so you can do
with open('text.json', 'r') as filename:
#your code
And you can access the file using the filename alias.
The benefit of that is that the context manager closes the file for you.
If you do manually as your first example you would need to manually call filename.close() after you used it to avoid file locking
When you open a file in python, you have to remember to close it when you're done.
So with your 1st line:
filename = open('text.json', 'r')
You'll need to remember to close the file.
The second version you have is typically used like this:
with open('text.json', 'r') as filename:
#block of code
This will automatically close the file after the block of code is run.
The other difference is the way you're naming the file object as "filename". You end up with the same object in both, just naming it in two different ways.
This question already has answers here:
Correct way to write line to file?
(17 answers)
Closed 5 years ago.
My code is like this .
inputfile=np.genfromtxt('test1.dat')
for data in inputfile:
lat=floor(data)+(floor(abs((data-floor(data))*100))/60)+....
print lat
In command window I can see
12.9579738889
12.9579736111
12.9579727778
12.9579719444
12.9579711111
12.9579702778
12.9579694444
.......
But I want to save it in a text file in my working directory .
I am not getting how to proceed. All attempts failed.
Please give suggestions.
Thanks in advance.
It's really simple. Use open to open the file (get a file object which encapsulates the file descriptor) and then simply write to that file. In a true Pythonic way you'll want to use a context manager (with open(..) as file), so the the file is closed automatically when out of context.
inputfile=np.genfromtxt('test1.dat')
with open("/path/to/output.file", "w") as f:
for data in inputfile:
lat=floor(data)+(floor(abs((data-floor(data))*100))/60)+....
f.write("%f\n" % lat)
You can do following. I used f-string to format output, which is available in Python >= 3.6, but you can you any version to do some calculation first and then output the value.
>>> with open('test1.dat') as f_in:
... with open('outputfile.txt', 'w') as f_out:
... for data in f_in:
... f_out.write(f"{floor(data)+(floor(abs((data-floor(data))*100))/60)}\n")
if your data has more than one values you can use split function:
lan, lot = (float(x) for x in data.split(' '))
where ' ' is your separator between those values
This question already has answers here:
Easiest way to read/write a file's content in Python
(7 answers)
Closed 6 years ago.
In Python, how to read a file content only (not including attribute and filename), like using InputStream in Java?
I need a method that works for various file formats
I've tried this
with open(filePath, "rb") as imageFile:
str = base64.b64encode(imageFile.read())
M=str.decode()
print(M)
The problem is, I will get error for any object after that block
The most basic way is like so:
with open("filename.txt") as f:
contents = f.read()
The variable contents will now contain a string of everything in the file. More information is in the Python Documentation (https://docs.python.org/3/tutorial/inputoutput.html).
This question already has answers here:
How do I append to a file?
(13 answers)
Closed 8 years ago.
This code actually overwrite the pre-existing content of out.txt, is there a way to make it print in the next line ?
with open(r'C:\out.txt', "w") as presentList:
print("Hello", file=presentList)
Use "a" instead of "w".
This appends new text at the end.
I think you'll want to open with "r+" instead (opening with "w" overwrites the file!). If you aren't partial to using with, you can do
f = open("C:/out.txt","r+")
f.readlines()
f.write("This is a test\n")
f.close()
The f.readlines() will ensure that you write to the end of the file instead of overwriting the first line if you need to write more. As the other person said, you can also open with "a" too
This question already has answers here:
How to print a file to stdout?
(11 answers)
Closed 9 years ago.
I'm trying to get Python to print the contents of a file:
log = open("/path/to/my/file.txt", "r")
print str(log)
Gives me the output:
<open file '/path/to/my/file.txt', mode 'r' at 0x7fd37f969390>
Instead of printing the file. The file just has one short string of text in it, and when I do the opposite (writing the user_input from my Python script to that same file) it works properly.
edit: I see what Python thinks I'm asking it, I'm just wondering what the command to print something from inside a file is.
It is better to handle this with "with" to close the descriptor automatically for you. This will work with both 2.7 and python 3.
with open('/path/to/my/file.txt', 'r') as f:
print(f.read())
open gives you an iterator that doesn't automatically load the whole file at once. It iterates by line so you can write a loop like so:
for line in log:
print(line)
If all you want to do is print the contents of the file to screen, you can use print(log.read())
open() will actually open a file object for you to read. If your intention is to read the complete contents of the file into the log variable then you should use read()
log = open("/path/to/my/file.txt", "r").read()
print log
That will print out the contents of the file.
file_o=open("/path/to/my/file.txt") //creates an object file_o to access the file
content=file_o.read() //file is read using the created object
print(content) //print-out the contents of file
file_o.close()