Substitute file content in Python [duplicate] - python

This question already has answers here:
Confused by python file mode "w+" [duplicate]
(11 answers)
Closed 8 years ago.
I imagine this is a question asked already twenty thousand times, but I cannot understand why the file is always empty. I want to open a file, remove a string from the whole file and then rewrite the content, but the file ends up being empty. This is the code I use:
f = open(filename,'w+')
f.write(f.read().replace(str_to_del,""))
f.close()
But the file is always empty. If I instead use "r+" then the content is appended and I have a duplicate text in the file. I'm using Python 3.3 . What am I missing?

Opening the file in w+ mode truncates the file. So, your f.read() is guaranteed to return nothing.
You can do this by opening the file in r+ mode, reading it, then calling f.seek(0), then writing. Or by opening the file in r mode, reading it, closing it, reopening it in w mode, and writing. Or, better, by writing a temporary file and moving it over the original (which gives you "atomic" behavior—no possibility of ending up with a half-written file).

Related

When I try and open/edit a .txt file in python, it deletes whatever is inside of the file. What is doing this? [duplicate]

This question already has answers here:
Confused by python file mode "w+" [duplicate]
(11 answers)
Closed 5 months ago.
Very short and simple. I am trying to create a highscore txt document for one of the games I'm making apart of a project. I want it to be able to keep the highest score ever reached in a text document so I can display it on the screen.
The file already exists, but whenever I load up the game, I get a "invalid literal for int() with base 10:" error. After looking, I realised this was because the file would delete anything inside of it when the program is started. Why is this? How can I fix it?
My code:
hisc = open("snakeScore.txt","w+")
highscore = hisc.read()
highscore_in_no = int(highscore)
if score>highscore_in_no:
hisc.replace(str(score))
highscore_in_no = score
Thats becuase You are using "w" when openning the file.
"w" Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
try using "r+" or "a"
From the documentation of Python3 for open:
r open for reading (default)
w open for writing, truncating the file first
'+' open for updating (reading and writing)
Then w+ will truncate the file before writing to it. You don't want that if you are required to read and store the content of it first.
Here's a working code, assuming that snakeScore.txt's content is a single line containing an integer, say "10":
score = 101
with open("snakeScore.txt", 'r+') as f:
highestscore = int(f.read())
if score > highestscore:
f.seek(0)
f.writelines(str(score))
The call to seek is needed in order to reset the pointer to the first line of the file, so we can rewrite the current line as opposed to adding a new one.

OS error 22 : File open and close on Azure "Invalid Argument" [duplicate]

This question already has answers here:
What is the python "with" statement designed for?
(11 answers)
Closed 6 months ago.
Running below code in Azure Blobstorage concurrently is throwing
OS Error 22:Invalid argument pointing to f.close()
Is using Close() when using with open() creating OS error 22 issues?
Understand that Close() is not required but want to understand the root cause of OS error 22
*with open(openfilepath,"w+") as f:
f.write(writeFile )
f.close()*
Check the below possibilities and try.
1
If f.close() to be used you may try this by not using with
f = open(file_name, 'w+') # open file in write mode
f.write('write content')
f.close()
BUT
It is good practice to use  with  keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes. once Python exits from the “with” block, the file is automatically closed. 
So Please Remove f.close() and try.
with open(file_name, 'w+') as f :
f.write('write content')
Refer this for more info.
2
If above doen’t work check the filepath : It might be due to some invalid characters present in the file path name: It should not contain few special characters.
See if file path is for example : "dbfs:/mnt/data/output/file_name.xlsx"
Check if “/” is there before dbfs ( say /dbfs:/mnt/…).Try Removing if present.
NOTE:
``r+'': Open for reading and writing. The stream is positioned at
the beginning of the file.
``w+'': Open for reading and writing. The file is created if it does
not exist, otherwise it is truncated. The stream is positioned at the
beginning of the file.
``a+'' : Open for reading and writing. The file is created if it does
not exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current end of
file, irrespective of any intervening fseek(3) or similar.
So try using other modes like r+ if w+ is not mandatory .See Python documentation
References:
1 , 2 ,3 , 4
Removing the F.close() fixed the issues when using With

How to fix "io.UnsupportedOperation: File not open for writing" Error? [duplicate]

This question already has answers here:
How to open a file for both reading and writing?
(4 answers)
Closed 3 years ago.
In simplest terms, when i try to run a short amount of code to delete the contents of a file and then rewrite stuff to that file, it pulls that error. I'm trying to get a temperature reading from a com port using the filewrite from CoolTerm, perhaps it's the fact that the file is being used by CoolTerm as well, so I can't edit it, but I'm unsure.
I've tried multiple ways to delete the file information e.g the file.close(), and others, but none seem to work.
while True:
file = open("test.txt","r")
file.truncate()
x = file.read()
x = x.split("\n")
print(x[0])
print(x[1])
time.sleep(3)
I expect the console to output the contents of file but it doesn't. Something that gives me a similar result of what i want would be the Console just outputting the last two entries of the file, rather than having to delete all of it than rewriting it.
Modified to r+ mode is ok, I have tested.
with open('./install_cmd', 'r+') as f:
print(f'truncate ago:{f.read()}')
f.truncate(0)
print(f'truncate after:{f.read()}')

python readline() output nothing [duplicate]

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

Reading lines beyond SUB in Python [duplicate]

This question already has answers here:
Line reading chokes on 0x1A
(2 answers)
Closed 4 years ago.
Newbie question. In Python 2.7.2., I have a problem reading text files which accidentally seem to contain some control characters. Specifically, the loop
for line in f
will cease without any warning or error as soon as it comes across a line containing the SUB character (ascii hex code 1a). When using f.readlines() the result is the same. Essentially, as far as Python is concerned, the file is finished as soon as the first SUB character is encountered, and the last value assigned line is the line up to that character.
Is there a way to read beyond such a character and/or to issue a warning when encountering one?
On Windows systems 0x1a is the End-of-File character. You'll need to open the file in binary mode in order to get past it:
f = open(filename, 'rb')
The downside is you will lose the line-oriented nature and have to split the lines yourself:
lines = f.read().split('\r\n') # assuming Windows line endings
Try opening the file in binary mode:
f = open(filename, 'rb')

Categories

Resources