Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python File Handling. Python language provides numerous built-in functions Some of the functions widely used for standard input and output operations.

Similar presentations


Presentation on theme: "Python File Handling. Python language provides numerous built-in functions Some of the functions widely used for standard input and output operations."— Presentation transcript:

1 Python File Handling

2 Python language provides numerous built-in functions Some of the functions widely used for standard input and output operations – input() – raw_input() – print()

3 File I/O Operations To read from or write to a file – Open a file – Read or write (perform operation) – Close the file

4 File Open Operation Python has a built-in function to open a file. open() It returns a file object, also called a handle, as it is used to read or modify the file accordingly. # open file in current directory >>> f = open("test.txt") # specifying full path >>> f = open("C:/Python33/README.txt")

5 Opening Files Prepares the file for reading A.Links the file variable with the physical file (references to the file variable are references to the physical file). B.Positions the file pointer at the start of the file. Format: 1 = open(, "r") Example: ( Constant file name) inputFile = open("data.txt", "r") OR (Variable file name: entered by user at runtime) fname = input("Enter name of input file: ") inputFile = open(fname, "r") 1 Examples assume that the file is in the same directory/folder as the Python program.

6 Python File Modes ModeDescription ‘r’Open a file for reading ‘w’Open a file for writing, Creates a new file if it does not exist or truncates the file if it exists ‘x’Open a file for exclusive creation. If the file already exists, the operation fails 'a'Open for appending at the end of the file without truncating it. Creates a new file if it does not exist 't‘Open in text mode 'b‘Open in binary mode ‘+’'+'Open a file for updating (reading and writing)

7 Opening Files in different Modes # equivalent to 'r' or 'rt' f = open("test.txt") # write in text mode f = open("test.txt",'w') # read and write in binary mode f = open("img.bmp",'r+b') # working with files in text mode with encoding type f = open("test.txt", mode = ‘r’,encoding = 'utf-8')

8 Reading Information From Files Typically reading is done within the body of a loop Each execution of the loop will read a line from the file into a string Format: for in : Example: for line in inputFile: # Echo file contents back onscreen print(line)

9 File Close Operation close() method on a file will free up the resources that were tied with the file. Python has a garbage collector to clean up unreferenced objects. What if the program encounters a runtime error and crashes before it reaches the end? The input file may remain ‘locked’ an inaccessible state because it’s still open. Format:.close() Example: inputFile.close() f = open("test.txt",encoding = 'utf-8') # perform file operations f.close()

10 Reading From Files: Putting It All Together inputFileName = input("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") for line in inputFile: sys.stdout.write(line) inputFile.close() print("Completed reading of file", inputFileName)

11 What You Need To Write Information To A File 1.Open the file and associate the file with a file variable (file is “locked” for writing). 2.A command to write the information. 3.A command to close the file.

12 Opening the File Format 1 : = open(, "w") Example: (Constant file name) outputFile = open("gpa.txt", "w") (Variable file name: entered by user at runtime) outputFileName = input("Enter the name of the output file to record the GPA's to: ") outputFile = open(outputFileName, "w") 1 Typically the file is created in the same directory/folder as the Python program.

13 Writing to a File Use the write() function in conjunction with a file variable. Format: outputFile.write(temp) Example: # Assume that temp contains a string of characters. outputFile.write (temp)

14 Writing To A File: Putting It All Together inputFileName = input("Enter the name of input file to read : ") outputFileName = input("Enter the name of the output file to record : ") inputFile = open(inputFileName, "r") outputFile = open(outputFileName, "w") print("Opening file", inputFileName, " for reading.") print("Opening file", outputFileName, " for writing.") gpa = 0

15 Writing To A File: Putting It All Together (2) for line in inputFile: if (line[0] == "A"): gpa = 4 elif (line[0] == "B"): gpa = 3 elif (line[0] == "C"): gpa = 2 elif (line[0] == "D"): gpa = 1 elif (line[0] == "F"): gpa = 0 else: gpa = -1 temp = str (gpa) temp = temp + '\n' print (line[0], '\t', gpa) outputFile.write (temp) inputFile.close () outputFile.close () print ("Completed reading of file", inputFileName) print ("Completed writing to file", outputFileName)

16 File Input: Alternate Implementation inputFileName = input ("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") line = inputFile.readline() while (line != ""): sys.stdout.write(line) line = inputFile.readline() inputFile.close() print("Completed reading of file", inputFileName)

17 Data Processing: Files Files can be used to store complex data given that there exists a predefined format. Format of the example input file: ‘ employees.txt ’,,

18 Example Program: data_processing.py inputFile = open ("employees.txt", "r") print ("Reading from file input.txt") for line in inputFile: name,job,income = line.split(',') last,first = name.split() income = int(income) income = income + (income * BONUS) print("Name: %s, %s\t\t\tJob: %s\t\tIncome $%.2f" %(first,last,job,income)) print ("Completed reading of file input.txt") inputFile.close() # EMPLOYEES.TXT Adama Lee,CAG,30000 Morris Heather,Heroine,0 Lee Bruce,JKD master,100000


Download ppt "Python File Handling. Python language provides numerous built-in functions Some of the functions widely used for standard input and output operations."

Similar presentations


Ads by Google