How to write integer to a file,.io.UnsupportedOperation: not writable - python

I'm trying to add 1 to the last integer of a file in excel. I can do this as the new_id is correct. However when I try to write the new_id to the file it does not work. Returning the io.UnsupportedOperation: not writable error message.
import csv
ID = []
file = open("customerID.csv","r")
for x in file:
ID.append(x)
lastid = int(ID[-1])
new_id = (lastid + 1)
file.close
print(lastid)
print (new_id)
file.write (str(new_id))
file.close

You opened the file for reading only when you specified 'r' in open. If you want to be able to write, you need to open it for writing. Use either 'a' if you want to write to the end of the file (appending), or 'w' if you want to erase the file prior to writing:
file = open("customerID.csv", "a")
Also note, your file.close lines aren't doing anything. You need to actually call the close method:
file.close() # Note the ()
And, you can't use file once close has been called on it.

Related

Python declaring file object but not opening a file

I am writing a Python program where I need to write to a file. I need an if condition to determine if I need to keep writing to same file or open a new file. How do I declare the file so that I can access it with both the if and else? Right now I'm making a test file before the loop just so I have access to the variable. How to avoid opening a TEST.txt file while still having a variable f that I can operate on?
f = open(outputFolder + "TEST.txt", 'w') # how to avoid opening TEST.txt here
while row:
#print(str(row[0]) + '|' + str(row[4]))
currentFileName = getFileName(str(row[0]))
# If coming up on new date open new file
if currentFileName != fileName:
f.close()
fileName = currentFileName
print("Processing: " + fileName)
f = open(outputFolder + fileName, 'w')
f.write(getLine(row))
# else write to current file
else:
f.write(getLine(row))
row = cursor.fetchone()
You didn't work out your logic before writing the program. What you describe in words does not match what you wrote. Start with the words, draw a flowchart, and then write your code.
In your posted program, you're trying to open currentFile multiple times, you don't initialize or change row, and it's not clear what you intend the program to do.
if [condition]:
filename = currentFileName
else:
filename = "TEST.txt"
f = open(filename)
for ... # whatever you're trying to do with your input and output,
# look up the proper method in a file-handling tutorial.

Python delete line and write over it

i have proplem here with my code
i am using for loop to save results in txt file
every time i use it it's saving the last line and delete the old line
here is code:
for i in domains:
requests.get(i)
if req.status_code == 200:
print('[+]:', i + '/')
file = open(save,'w')
file.write(domain)
file.close()
so after run the code it's save the last domain or last results and delete the old results
so i want solution
thanks.
Open the file in append mode:
open(filename,'a')
Your code should be:
for i in domains:
requests.get(i)
if req.status_code == 200:
print('[+]:', i + '/')
file = open(save,'a')
file.write(i)
file.close()
Try open it with a instead of w, so:
file = open(save, 'a')
it should appends to the file instead of writing to it
You sould use 'a' instead of 'w' in "file = open(save,'w')"
The problem here is arising because you are opening the file for writing on every iteration of the loop. Because you are opening the file with mode 'w', the file is being overwritten every time. (See documentation.)
It would be better to open the file once only, outside the loop.
For example:
file = open(save, 'w')
for i in domains:
# do some stuff...
file.write(some_data)
file.close()
You can also use with in conjuction with the open function:
with open(save, 'w') as file:
for i in domains:
# do some stuff...
file.write(some_data)
In this case, there is no need for an explicit call to file.close(). This will be done automatically when the loop ends, or even if something happens inside the with block like an exception being raised (i.e. error occurring) or a return from the function (if applicable).
Be aware that because of output buffering, data written to the file during one iteration might not actually get written to the file until some later iteration or after the file is closed. If this would be a problem, then you can insert a flush call to force a low-level write so that other processes can see the data:
with open(save, 'w') as file:
for i in domains:
# do some stuff...
file.write(some_data)
file.flush()
If there is some reason why you need to open the file inside the loop, then you could open it in append mode using 'a', and the data will be written after the end of the existing file. (Again, see the documentation linked earlier.) For example:
for i in domains:
# do some stuff...
file = open(save, 'a')
file.write(some_data)
file.close()
or again, better like this:
for i in domains:
with open(save, 'a') as file:
# do some stuff...
file.write(some_data)
Be aware that if the output file already exists before the program is started, then the contents of the existing file will remain because you are always opening it in append mode. Depending on your application, this might or might not be desirable.

How can you append and write to the same text file in python 3?

In one of my games, I need to append to the end of the game saves file if I the user is new or change the balance in the file if the user already has a game save. This requires me to open the file separately in write and append modes. Is there a way I could do this sumultaneously?
def write_to_txt(self):
if self.saved_game:
with open("Game Saves.txt", "w") as f:
new_saved_game = self.list_saved_game[0] + self.list_saved_game[1][:10] + str(self.balance) + "\n"
f.write(''.join(self.contents_of_txt_file).replace(self.saved_game, new_saved_game))
else:
with open("Game Saves.txt", "a") as f:
f.write("User: {}\nBalance = {}\n".format(self.name, self.balance))
It seems to me that you want a way to delete the contents of the file while in append mode? You could open it in append mode and then use the .truncate() method when you want to start writing from a clean file (as you would if you opened it in write mode).
See this answer: How to erase the file contents of text file in Python?
You can use something like:
with open("Game Saves.txt", ('a' if self.saved_game else 'w')) as f:
<rest of the code>

Not able to clear file Contents

I have a file which has below data.
edit 48
set dst 192.168.4.0 255.255.255.0
set device "Tague-VPN"
set comment "Yeshtel"
edit 180
set dst 64.219.107.45 255.255.255.255
set device "Austin-Backup"
set comment "images.gsmc.org"
I want to copy the commands under edit only if Set device is Austin-Backup.
string = 'set device'
word = '"Austin-Backup"'
with open('test.txt') as oldfile, open('script.txt', 'w') as newfile:
for line in oldfile:
newfile.write(line)
newfile.write('\n')
if string not in line:
pass
elif string in line:
if word not in line:
a = open('script.txt', 'w')
a.close()
else:
pass
I am trying to write test file content to new file(script) and if command "set comment "Yeshtel"" is found i want to delete contents in new file. I tried to delete but its not happening. I am new to Python, Can you please tell what is the Prob??
I got to know that reopening the same file in Write mode will clear the contents..
I suspect the issue is that you have the same file open twice, once as newfile and a second time as a. While it should be truncated when you open it as a and then close it, the writes you made on newfile may still appear if the filesystem had cached them until after the truncated version was written.
I suggest only opening the file once. When you need to truncate it, call the truncate method on it.
if word not in line:
newfile.truncate()
If you might write more to the file after truncating, you should probably also seek back to the start position (e.g. newfile.seek(0)). If you're going to be done with the file after truncating it, that step is not needed.
Should be something like this
temp_lines = []
last_line_was_edit = False
found_keyword = False
keyword = "Austin-Backup"
with open('test.txt') as oldfile, open('script.txt', 'w') as newfile:
for line in oldfile:
if last_line_was_edit and temp_lines:
if found_keyword:
newfile.writelines(temp_lines)
temp_lines = []
if line.startswith("edit"):
last_line_was_edit = True
else:
if keyword in line:
found_keyword = True
temp_lines.append(line)
Please note that you should not open the file twice. Just use an temporary variable and write only what have to be written

Writing to a new file if it doesn't exist, and appending to a file if it does

I have a program which writes a user's highscore to a text file. The file is named by the user when they choose a playername.
If the file with that specific username already exists, then the program should append to the file (so that you can see more than one highscore). And if a file with that username doesn't exist (for example, if the user is new), it should create a new file and write to it.
Here's the relevant, so far not working, code:
try:
with open(player): #player is the varible storing the username input
with open(player, 'a') as highscore:
highscore.write("Username:", player)
except IOError:
with open(player + ".txt", 'w') as highscore:
highscore.write("Username:", player)
The above code creates a new file if it doesn't exist, and writes to it. If it exists, nothing has been appended when I check the file, and I get no errors.
Have you tried mode 'a+'?
with open(filename, 'a+') as f:
f.write(...)
Note however that f.tell() will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.
It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".
import os
player = 'bob'
filename = player+'.txt'
if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not
highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()
Just open it in 'a' mode:
a Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.
with open(filename, 'a') as f:
f.write(...)
To see whether you're writing to a new file, check the stream position. If it's zero, either the file was empty or it is a new file.
with open('somefile.txt', 'a') as f:
if f.tell() == 0:
print('a new file or the file was empty')
f.write('The header\n')
else:
print('file existed, appending')
f.write('Some data\n')
If you're still using Python 2, to work around the bug, either add f.seek(0, os.SEEK_END) right after open or use io.open instead.
Notice that if the file's parent folder doesn't exist you'll get the same error:
IOError: [Errno 2] No such file or directory:
Below is another solution which handles this case:
(*) I used sys.stdout and print instead of f.write just to show another use case
# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print_to_log_file(folder_path, "Some File" ,"Some Content")
Where the internal print_to_log_file just take care of the file level:
# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):
#1) Save a reference to the original standard output
original_stdout = sys.stdout
#2) Choose the mode
write_append_mode = 'a' #Append mode
file_path = folder_path + file_name
if (if not os.path.exists(file_path) ):
write_append_mode = 'w' # Write mode
#3) Perform action on file
with open(file_path, write_append_mode) as f:
sys.stdout = f # Change the standard output to the file we created.
print(file_path, content_to_write)
sys.stdout = original_stdout # Reset the standard output to its original value
Consider the following states:
'w' --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a' --> Append to file
'a+' --> Append to file, Create it if doesn't exist
In your case I would use a different approach and just use 'a' and 'a+'.
Using the pathlib module (python's object-oriented filesystem paths)
Just for kicks, this is perhaps the latest pythonic version of the solution.
from pathlib import Path
path = Path(f'{player}.txt')
path.touch() # default exists_ok=True
with path.open('a') as highscore:
highscore.write(f'Username:{player}')

Categories

Resources