File Object.doc
File Object.doc
The file
objects contain methods and attributes which latter can be used to retrieve
information or manipulate the file you opened.
File Operations
The file is a named location on the disk to store related information, as the file
is having some name and location, it is stored in the hard disk. In Python, file
operation is performed in the following order -
Opening a file.
Read or Write operation.
Closing a file.
Mode Description
Open a file for writing. Creates a new file if it does not exist or truncates
‘w’
the file if it exists.
Open a file for exclusive creation. If the file already exists, the operation
‘x’
fails.
‘a’ Open for appending at the end of the file without truncating it. Creates a
Mode Description
f.close()
Output
Reading a Text file
There are various ways to read a text file in Python, some of them are as follows
below.
Extracting all characters of a string
Reading certain numbers of character
Reading a file line by line
Looping over a file object
Splitting Lines in a Text File
Extracting all characters of a string
In case you want to extract a string that contains all characters in the file. We
can use the following method:
file.read()
Example
f = open("textfile.txt", "r")
f.read()
Output
'Hello, Python\nThis is our first line\nThis is our second line\nWhy writing
more?, Because we can :)'
Reading certain numbers of character
If you want to read a certain number of characters in the string from a file, we
can use the method as shown below -
f = open("textfile.txt", "r")
print(f.read(13))
Output
Hello, Python
Reading a file line by line
However, if you want to read a file line by line then you can use the readline()
function.
Example
f = open("textfile.txt", "r")
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
Output
Hello, Python
Writing to a file
Writing to a file is simple, you just need to open the file and pass on the text you
want to write to a file. We can use the open() method to append data to an
existing file. Use the EOL character to start a new line after you write data to
the file.
Example
f = open("textfile.txt", "w")
f.write("There are tons to reason to 'fall in love with PYTHON'")
f.write("\nSee, i have added one more line :).")
f.close()
f = open("textfile.txt", "r")
for line in f:
print(line)
Output
There are tons to reason to 'fall in love with PYTHON'
See, i have added one more line :).
Closing a file
Once you’re done working on a file, you have to use the f.close() command to
end things. With this, we’ve closed the file completely, terminating all the
resources in use and freeing them up for the system to use elsewhere.
Example
f = open("textfile.txt", "r")
f.close()
f.readlines()
Output
Once the file is closed, any attempt to use the file object will through an error.
Traceback (most recent call last):
File "<pyshell#95>", line 1, in <module>
f.readlines()
ValueError: I/O operation on closed file.
Using "with" Statement
The with statement can be used with file objects. Using the two (with statement
& file objects) we get, much cleaner syntax and exception handling in our
program.
Another advantage is that any files opened will be closed automatically once we
are done with file operations
Syntax
with open(“filename”) as file:
Example:
In this example, the file is automatically closed at the end of the with block, so
there is no need to call the close() method explicitly.
Open Compiler
with open("example.txt", "w") as file:
file.write("This is an example using the with statement.")
print ("File closed successfully!!")
Output
File closed successfully!!
Example:
f = open("myfile.txt", "r")
f.close()
read()
The read () method is used to read the content from file. To read a file in
Python, we must open the file in reading mode.
Syntax:
Fileobject.read([size])
Where ‘size’ specifies number of bytes to be read.
myfile.txt
function open() to open a file.
method read() to read a file.
readline()
Python facilitates us to read the file line by line by using a function readline().
The readline() method reads the lines of the file from the beginning, i.e., if we
use the readline() method two times, then we can get the first two lines of the
file.
Syntax:
Fileobject.readline()
myfile.txt
function open() to open a file.
method read() to read a file.
write()
The write () method is used to write the content into file. To write some text to a
file, we need to open the file using the open method with one of the following
access modes.
w: It will overwrite the file if any file exists. The file pointer point at the
beginning of the file in this mode.
Syntax:
Fileobject.write(content)
myfile.txt
function open() to open a file.
method read() to read a file.
It will append the existing file. The file pointer point at the end of the file.
myfile.txt
function open() to open a file.
method read() to read a file.
File Positions
Methods that set or modify the current position within the file
☞ tell()
The tell() method returns the current file position in a file stream. You can
change the current file position with the seek() method.
Syntax:
Fileobject.tell()
myfile.txt
function open() to open a file.
method read() to read a file.
seek()
The seek() method sets and returns the current file position in a file stream.
Syntax:
Fileobject.seek(offset)
myfile.txt
function open() to open a file.
method read() to read a file.
Example:
f = open("myfile.txt", "r")
print(f.seek(9))
print(f.read())
f.close();
First We moved 9bytes with seek function and then started reading
File Built-in Attributes
Python Supports following built-in attributes, those are
file.name - returns the name of the file which is already opened.
file.mode - returns the access mode of opened file.
file.closed - returns true, if the file closed, otherwise false.
Example:
f = open ("myfile.txt", "r")
print(f.name)
print(f.mode)
print(f.closed)
f.close()
print(f.closed)
Output:
myfile.txt
r
False
True