Here’s how you read a file, and then write to it (overwriting any existing data), without closing and reopening:
with open(filename, "r+") as f:
data = f.read()
f.seek(0)
f.write(output)
f.truncate()
More Related Contents:
- Writing a list to a file with Python
- Get last n lines of a file, similar to tail
- open() gives FileNotFoundError/IOError: Errno 2 No such file or directory
- Writing a Python list of lists to a csv file
- How to open a file using the open with statement
- Writing a list to a file with Python, with newlines
- Read from a log file as it’s being written using python
- Python Random Access File
- Open files in ‘rt’ and ‘wt’ modes
- What is the difference between rb and r+b modes in file objects [duplicate]
- python write string directly to tarfile
- how to count the total number of lines in a text file using python
- How to populate Objects in a an existing file [closed]
- python program to divide numbers in file in selected order [closed]
- UnicodeDecodeError: ‘charmap’ codec can’t decode byte X in position Y: character maps to
- Python convert csv to xlsx
- What is the perfect counterpart in Python for “while not EOF”
- Python list directory, subdirectory, and files
- What does ‘wb’ mean in this code, using Python?
- How to save a list to a file and read it as a list type?
- Replace string within file contents [duplicate]
- How to solve “OSError: telling position disabled by next() call”
- An integer is required? open()
- Determining Whether a Directory is Writeable
- Find all CSV files in a directory using Python
- Treat binary data as a file object?
- How do I create a file in python without overwriting an existing file
- Unicode encoding for filesystem in Mac OS X not correct in Python?
- Python not able to open file with non-english characters in path
- Writing to a new file if it doesn’t exist, and appending to a file if it does