file = open("data.txt", "a" )
file.write( "Hello World" )
file.close()
Note that for the opening world a , if you want to write on the line, you can use the line break \n :
file = open ("data.txt","a" )
file.write("\n Hello World" )
file.close()
The keyword with
There is another shorter syntax which allows to emancipate oneself from the problem of closing the file: the keyword with .
Here is the syntax:
with open( "data.txt","r" ) as file :
print file.read ()
Nmap
"mmap" is a Python library that allows mapping files or memory segments in Python. It provides an interface that resembles Python arrays, allowing file or heap data to be accessed as if it were a Python array.
Using "mmap" can be a more efficient approach to accessing data from a file or memory segment than using standard read and write functions, as it maps the file or the memory segment in memory and to access the data directly, without going through the overhead of the Python interpreter. This can be particularly useful for processing large amounts of data or for accessing data repeatedly.
Here's how to use "mmap" to read a file in Python:
import mmap
# Open the file in read mode and get its size
with open('my_file.txt', 'r') as f:
size = f.seek(0, 2)
f.seek(0)
# Create an mmap object from file
mm = mmap.mmap(f.fileno(), size)
# Read contents of file using mmap object
contents = mm.read()
# Print contents of file
print(contents)