Python - Only last line is saved to file - python

I'm trying to output the result of my script into a text file. The script is working fine, the only problem is when results are saved into the text file (output.txt), only last line is being saved,not the whole thing? I'm not sure what I'm doing wrong here. any suggestions will be appreciated.
Cheer!
try:
if 'notavailable' not in requests.get('url' + str(service) + '&username=' + str(username), headers={'X-Requested-With': 'XMLHttpRequest'}).text:
result = service + '\t' + " > " + username + " > " 'Available'
print result
f = open("output.txt", "w")
f.write(result + "\n")
f.close()
else:
print service + '\t' + " > " + username + " > " 'Not Available'
except Exception as e:
print e

you need to write
f = open("output.txt", "a")
This will append the file, rather than write over whatever else you put in it.

In every iteration you are opening the file, erasing its content, writing and closing. It is much better to open it only once:
f = open('output.txt', 'w')
# do loop
f.write(stuff)
f.close()
Or, much better:
with open('output.txt', 'w') as f:
while loop:
f.write(stuff)
This method is not only cleaner, but also performs much better, as you can cache the contents of the file, and use the minimal number of OS calls.

I'm going to take a wild guess and assume that all of this code happens inside a loop. Each time through the loop, you write one more line, but at the end, you only have the last line.
If that's the problem, here's the issue:
f = open("output.txt", "w")
When you open a file in 'w' mode, that truncates any existing file.
To fix this, either open the file once, outside the loop, instead of over and over again, or open it in 'a' mode or 'r+' mode or some other mode that doesn't truncate the file.
The documentation for the open function, or the inline help in the interactive interpreter, explains what all the different modes mean.

Did you try with parameter 'a'
So:
f = open("output.txt", "a")
That will open the file with pointer at the end.
http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

Related

F.write has returned 'io.UnsupportedOperation: not writable' and I don't know why

I am trying to write to a leaderboard text file and I can't tell why but it keeps giving me the error code 'io.UnsupportedOperation: not writable'. I am trying to write the \n to create a new line but it gives the error code, I tried it without that and it still gives the same error for f.write(writeToFile).
The relevant code is here:
with open('leaderboard.txt') as f:
stringScore = str(score)
writeToFile = username + "#" + stringScore
f.write("\n")
f.write(writeToFile)
If you have any questions, as this is part of a bigger project I will try and get back to you but I'm not super active, thanks for any help you can give.
You have to specify in what mode you are opening a file. By default it opens in read-only mode do this instead:
with open('leaderboard.txt',"w") as f:
stringScore = str(score)
writeToFile = username + "#" + stringScore
f.write("\n")
f.write(writeToFile)

How do I stop new data from python replacing old data in a csv file? [duplicate]

The code below is what I have so far. When it writes to the .csv it overwrites what I had previously written in the file.How can I write to the file in such a way that it doesn't erase my previous text.(The objective of my code is to have a person enter their name and have the program remember them)
def main(src):
try:
input_file = open(src, "r")
except IOError as error:
print("Error: Cannot open '" + src + "' for processing.")
print("Welcome to Learner!")
print("What is your name? ")
name = input()
for line in input_file:
w = line.split(",")
for x in w:
if x.lower() == name.lower():
print("I remember you "+ name.upper())
else:
print("NO")
a = open("learner.csv", "w")
a.write(name)
a.close()
break
if __name__ == "__main__":
main("learner.csv")
You need to append to file the next time. This can be done by opening the file in append mode.
def addToFile(file, what):
f = open(file, 'a').write(what)
change open("learner.csv", "w") to open("learner.csv", "a")
The second parameter with open is the mode, w is write, a is append. With append it automatically seeks to the end of the file.
You'll want to open the file in append-mode ('a'), rathen than write-mode ('w'); the Python documentation explains the different modes available.
Also, you might want to consider using the with keyword:
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
>>> with open('/tmp/workfile', 'a') as f:
... f.write(your_input)

Problems writing to text file

I'm having a little trouble writing data to text files with python. Basically, what I want to do is read information in a text file, update the read text, and write the updated information back to the same text file. Reading and updating the text is easy enough, however, I run into difficulties when I try to write the updated text back to the text file.
The text file is very basic and consists of three lines. Here it is:
48850
z_merged_shapefiles
EDRN_048850
I used the code below to try and update it but got this error: 'file' object has no attribute 'writeline'
Here is the code that I used:
fo = open("C:\\Users\\T0015685\\Documents\\Python\\Foo1.txt", "r")
read1 = fo.readline()
read2 = fo.readline()
read3 = fo.readline()
fo.close()
edrn_v = int(read1) + 1
newID = "EDRN_" + str(edrn_v)
fo = open("C:\\Users\\T0015685\\Documents\\Python\\Foo1.txt", "w")
fo.writeline(edrn_v)
fo.writeline(read2)
fo.writeline(newID)
Although there is a readline there is no analog writeline.
You can either use a write and append a '\n' to terminate a line
with open("C:\\Users\\T0015685\\Documents\\Python\\Foo1.txt", "w") as fo:
fo.write(edrn_v + '\n')
fo.write(read2 + '\n')
fo.write(newID + '\n')
Or put all the variables in a list and use writelines.
with open("C:\\Users\\T0015685\\Documents\\Python\\Foo1.txt", "w") as fo:
fo.writelines([edrn_v, read2, newID])
Note
I am using the with open statement
with open() as f:
So you don't have to manage the open and close yourself
f.open()
f.read()
f.close()

storing results into a file after multiple runs python

I have made an executable script in Python which takes as a command line argument the name of a file. The script runs and outputs a number. I have several files for which I have to run the script and I want to store all the results in a separate file called results.txt. The file should look like this:
name_of_file_1 result_number_1
name_of_file_2 result_number_2
name_of_file_3 result_number_3
...
name_of_file_n result_number_n
This is what I tried so far, but every time the name of the file and the result are overwritten.
args = sys.argv[1]
f = open('results.txt', 'w')
f.write(args + " " + str(len(i)) + "\n")
f.close()
How can I do this?
You can use the append mode instead of the write mode as follows:
f = open('results.txt', 'a')
f.write(args + " " + str(len(i)) + "\n")
f.close()
The append mode adds on to the existing file whereas the write mode simply clears the file or overwrites it.
Use:
f = open('results.txt', 'a')

How to write to CSV and not overwrite past text

The code below is what I have so far. When it writes to the .csv it overwrites what I had previously written in the file.How can I write to the file in such a way that it doesn't erase my previous text.(The objective of my code is to have a person enter their name and have the program remember them)
def main(src):
try:
input_file = open(src, "r")
except IOError as error:
print("Error: Cannot open '" + src + "' for processing.")
print("Welcome to Learner!")
print("What is your name? ")
name = input()
for line in input_file:
w = line.split(",")
for x in w:
if x.lower() == name.lower():
print("I remember you "+ name.upper())
else:
print("NO")
a = open("learner.csv", "w")
a.write(name)
a.close()
break
if __name__ == "__main__":
main("learner.csv")
You need to append to file the next time. This can be done by opening the file in append mode.
def addToFile(file, what):
f = open(file, 'a').write(what)
change open("learner.csv", "w") to open("learner.csv", "a")
The second parameter with open is the mode, w is write, a is append. With append it automatically seeks to the end of the file.
You'll want to open the file in append-mode ('a'), rathen than write-mode ('w'); the Python documentation explains the different modes available.
Also, you might want to consider using the with keyword:
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
>>> with open('/tmp/workfile', 'a') as f:
... f.write(your_input)

Categories