Difference between revisions of "File Handling - Python"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Created page with "=Python & Files= Python has built in functions to read and write files. ==Open== The open() function allows you to essentially create a stream to a file, you need to specify...")
 
(No difference)

Latest revision as of 19:55, 20 June 2018

Python & Files

Python has built in functions to read and write files.

Open

The open() function allows you to essentially create a stream to a file, you need to specify the file to open and the mode you wish to use. The mode indicates, how the file is going to be opened "r" for reading, "w" for writing and "a" for a appending.

By default, when only the filename is passed, the open function opens the file in read mode.

filename = "hello.txt"
file = open(filename, "r")
for line in file:
   print(line)

Read

The read functions contains different methods, read(),readline() and readlines()

read()		#return one big string
readline	#return one line at a time
readlines	#returns a list of lines

Write

This method writes a sequence of strings to the file.

write ()	#Used to write a fixed sequence of characters to a file
writelines()	#writelines can write a list of strings.

Append

The append function is used to append to the file instead of overwriting it.

To append to an existing file, simply open the file in append mode ("a"):

Close

When you’re done with a file, use close() to close it and free up any system resources taken up by the open file.

File Handling Examples

To open a text file, use:

fh = open("hello.txt", "r")

To read a text file, use:

fh = open("hello.txt","r")
print(fh.read())

To read one line at a time, use:

fh = open("hello".txt", "r")
print(fh.readline())

To read a list of lines use:

fh = open("hello.txt.", "r")
print(fh.readlines())

To write to a file, use:

fh = open("hello.txt","w")
write("Hello World")
fh.close()

To write to a file, use:

fh = open("hello.txt", "w")
lines_of_text = ["a line of text", "another line of text", "a third line"]
fh.writelines(lines_of_text)
fh.close()

To append to file, use:

fh = open("Hello.txt", "a")
write("Hello World again")
fh.close()

To close a file, use

fh = open("hello.txt", "r")
print(fh.read())
fh.close()