Note: Make sure the file exists, or else you will get an error.
Open a File on the Server
Assume we have the following file, located in the same folder as Python:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the
content of the file:
Example
f = open("demofile.txt")
print(f.read())
If the file is located in a different location, you will have to specify the file path, like this:
Example
Open a file on a different location:
f = open("D:\\myfiles\welcome.txt")
print(f.read())
Using the with statement
You can also use the with statement when opening a file:
Example
Using the with keyword:
with open("demofile.txt") as f:
print(f.read())
Then you do not have to worry about closing your files, the with statement takes care of
that.
Close Files
It is a good practice to always close the file when you are done with it.
If you are not using the with statement, you must write a close statement in order to close
the file:
Example
Close the file when you are finished with it:
f = open("demofile.txt")
print(f.readline())
f.close()
Note: You should always close your files. In some cases, due to buffering, changes made
to a file may not show until you close the file.
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example
Return the 5 first characters of the file:
with open("demofile.txt") as f:
print(f.read(5))
Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
with open("demofile.txt") as f:
print(f.readline())
By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
with open("demofile.txt") as f:
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
Example
Loop through the file line by line:
with open("demofile.txt") as f:
for x in f:
print(x)
Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example
Open the file "demofile.txt" and append content to the file:
with open("demofile.txt", "a") as f:
f.write("Now the file has more content!")
#open and read the file after the appending:
with open("demofile.txt") as f:
print(f.read())
Overwrite Existing Content
To overwrite the existing content to the file, use the w parameter:
Example
Open the file "demofile.txt" and overwrite the content:
with open("demofile.txt", "w") as f:
f.write("Woops! I have deleted the content!")
#open and read the file after the overwriting:
with open("demofile.txt") as f:
print(f.read())
Note: the "w" method will overwrite the entire file.
Create a New File
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exists
"a" - Append - will create a file if the specified file does not exists
"w" - Write - will create a file if the specified file does not exists
Example
Create a new file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created.
Note: If the file already exist, an error will be raised.
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
ExampleGet your own Python Server
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
Check if File exist:
To avoid getting an error, you might want to check if the file exists before you try to delete
it:
Example
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.
Python File I/O - Read and Write Files
In Python, the IO module provides methods of three types of IO
operations; raw binary files, buffered binary files, and text files. The
canonical way to create a file object is by using the open() function.
Any file operations can be performed in the following three steps:
1. Open the file to get the file object using the
built-in open() function. There are different access modes, which
you can specify while opening a file using the open() function.
2. Perform read, write, append operations using the file object
retrieved from the open() function.
3. Close and dispose the file object.
Reading File
File object includes the following methods to read data from the file.
● read(chars): reads the specified number of characters starting
from the current position.
● readline(): reads the characters starting from the current reading
position up to a newline character.
● readlines(): reads all lines until the end of file and returns a list
object.
The following C:\myfile.txt file will be used in all the examples of reading
and writing files.
C:\myfile.txt
Copy
This is the first line.
This is the second line.
This is the third line.
The following example performs the read operation using
the read(chars) method.
Example: Reading a File
Copy
f = open('C:myfile.txt') # opening a file
lines = f.read() # reading a file
print(lines) #'This is the first line.
This is the second line.
This is the third line.'
f.close() # closing file object
Above, f = open('C:\myfile.txt') opens the myfile.txt in the default read
mode from the current directory and returns a file
object.f.read() function reads all the content until EOF as a string. If
you specify the char size argument in the read(chars) method, then it
will read that many chars only.f.close() will flush and close the stream.
Reading a Line
The following example demonstrates reading a line from the file.
Example: Reading Lines
Copy
f = open('C:myfile.txt') # opening a file
line1 = f.readline() # reading a line
print(line1) #'This is the first line.
'
line2 = f.readline() # reading a line
print(line2) #'This is the second line.
'
line3 = f.readline() # reading a line
print(line3) #'This is the third line.'
line4 = f.readline() # reading a line
print(line4) #''
f.close() # closing file object
As you can see, we have to open the file in 'r' mode.
The readline() method will return the first line, and then will point to the
second line in the file.
Reading All Lines
The following reads all lines using the readlines() function.
Example: Reading a File
Copy
f = open('C:myfile.txt') # opening a file
lines = f.readlines() # reading all lines
print(lines) #'This is the first line.
This is the second line.
This is the third line.'
f.close() # closing file object
The file object has an inbuilt iterator. The following program reads the
given file line by line until StopIteration is raised, i.e., the EOF is
reached.
Example: File Iterator
Copy
f=open('C:myfile.txt')
while True:
try:
line=next(f)
print(line)
except StopIteration:
break
f.close()
Use the for loop to read a file easily.
Example: Read File using the For Loop
Copy
f=open('C:myfile.txt')
for line in f:
print(line)
f.close()
Output
This is the first line. This is the second line. This is the third
line.
Reading Binary File
Use the 'rb' mode in the open() function to read a binary files, as shown
below.
Example: Reading a File
Copy
f = open('C:myimg.png', 'rb') # opening a binary file
content = f.read() # reading all lines
print(content) #print content
f.close() # closing file object
Writing to a File
The file object provides the following methods to write to a file.
● write(s): Write the string s to the stream and return the number
of characters written.
● writelines(lines): Write a list of lines to the stream. Each line
must have a separator at the end of it.
Create a new File and Write
The following creates a new file if it does not exist or overwrites to an
existing file.
Example: Create or Overwrite to Existing File
Copy
f = open('C:myfile.txt','w')
f.write("Hello") # writing to file
f.close()
# reading file
f = open('C:myfile.txt','r')
f.read() #'Hello'
f.close()
In the above example, the f=open("myfile.txt","w") statement
opens myfile.txt in write mode, the open() method returns the file object
and assigns it to a variable f.'w' specifies that the file should be
writable. Next, f.write("Hello") overwrites an existing content of
the myfile.txt file. It returns the number of characters written to a file,
which is 5 in the above example. In the end, f.close() closes the file
object.
Appending to an Existing File
The following appends the content at the end of the existing file by
passing 'a' or 'a+' mode in the open() method.
Example: Append to Existing File
Copy
f = open('C:myfile.txt','a')
f.write(" World!")
f.close()
# reading file
f = open('C:myfile.txt','r')
f.read() #'Hello World!'
f.close()
Write Multiple Lines
Python provides the writelines() method to save the contents of a list
object in a file. Since the newline character is not automatically written
to the file, it must be provided as a part of the string.
Example: Write Lines to File
Copy
lines=["Hello world.
", "Welcome to TutorialsTeacher.
"]
f=open("D:myfile.txt", "w")
f.writelines(lines)
f.close()
Opening a file with "w" mode or "a" mode can only be written into and
cannot be read from. Similarly "r" mode allows reading only and not
writing. In order to perform simultaneous read/append operations, use
"a+" mode.
Writing to a Binary File
The open() function opens a file in text format by default. To open a file
in binary format, add 'b' to the mode parameter. Hence the "rb" mode
opens the file in binary format for reading, while the "wb" mode opens
the file in binary format for writing. Unlike text files, binary files are
not human-readable. When opened using any text editor, the data is
unrecognizable.
The following code stores a list of numbers in a binary file. The list is
first converted in a byte array before writing. The built-in
function bytearray() returns a byte representation of the object.
Example: Write to a Binary File
Copy
f=open("binfile.bin","wb")
num=[5, 10, 15, 20, 25]
arr=bytearray(num)
f.write(arr)
f.close()