“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
Python files / directories part16
1. Prof. Neeraj Bhargava
Vishal Dutt
Department of Computer Science, School of
Engineering & System Sciences
MDS University, Ajmer
2. The File Objects provides a set of methods or
functions to perform various tasks in the file.
Two common tasks are reading a file and writing into a
file.
The write() Method
The write() method writes any string to an open file.
It is important to note that Python strings can have
binary data and not just text.
Reading and Writing Files
3. The write() method does not add a newline character ('n')
to the end of the string .
Syntax:
fileObject.write(string)
Example
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.nYeah its great!!n")
# Close opend file
fo.close()
4. "a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example 1:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Example 2:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
5. Create a New Empty 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
exist
f = open("myfile.txt", "x")
Result: a new empty file is created!
6. The read() Method
The read() method reads a string from an open file.
Syntax:
fileObject.read([count])
Here passed parameter is the number of bytes to be read
from the opened file.
This method starts reading from the beginning of the
file and if count is missing, then it tries to read as much
as possible, maybe until the end of file.
7. Example:
f = open("demofile.txt", "r")
print(f.read())
Example:
# Open a file
fo = open(“demofile.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
Hello! Welcome to
demofile.txt
This file is for testing
purposes.
Good Luck!
demofile.text
8. Read Lines
You can return one line by using
the readline() method:
Example:
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two
first lines:
Hello! Welcome to demofile.txt
9. Questions
Illustrate File reading in Python/
Illustrate Writing into the file in Python.
How can you print line by line from a file using loops?
Explain with Example.