Introduction to Python File Input/Output Operations

introduction to computing using python n.w
1 / 11
Embed
Share

Learn how to work with files and the file system in Python. Understand file opening, processing, and closing operations. Explore different file modes and how to access files for reading, writing, and appending. Enhance your Python skills in managing file operations efficiently.

  • Python Basics
  • File Handling
  • Data Input/Output
  • File Operations
  • Python Programming

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Introduction to Computing Using Python Text Data, File I/O File Input/Output

  2. Introduction to Computing Using Python Files and the file system root folder / / The file system is the OS component that organizes files and provides a way to create, access, and modify files Applications Applications bin bin Users Users var var Mail.app Mail.app Firefox.app Firefox.app messi messi Shared Shared poem.txt Files are organized into a tree structure folders (or directories) folders (or directories) regular files Contents Contents image.jpg poem.txt Canon Canon MacOS MacOS binary file text file While every file and folder has a name, it is the file pathname that identifies the file Mail Relative pathnames (relative to current working directory Users) messi/poem.txt messi/image.jpg Shared Absolute pathnames /var/poem.txt /Users/messi/poem.txt /Applications/Mail.app/

  3. Introduction to Computing Using Python Opening and closing a file Processing a file consists of: 1. Opening the file 2. Reading from and/or writing to the file 3. Closing the file File mode 'r' is used to open a file for reading (rather than, say, writing) Built-in function open() is used to open a file The first input argument is the file pathname, whether absolute or relative with respect to the current working directory The second (optional) argument is the file mode Returns a file object >>> infile = open('sample.txt') Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt' >>> >>> infile = open('example.txt', 'r') >>> >>> infile.close() >>> >>> infile = open('sample.txt') Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt' 'sample.txt' >>> infile = open('example.txt', 'r') >>> infile = open('sample.txt') Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> infile = open('sample.txt') IOError: [Errno 2] No such file or directory: A file object is of a type that supports several file methods, including method close() that closes the file

  4. Introduction to Computing Using Python Open file mode The file mode defines how the file will be accessed Mode r w a r+ t b Description Reading (default) Writing (if file exists, content is wiped) Append (if file exists, writes are appended) Reading and Writing Text (default) Binary >>> infile = open('example.txt', 'rt') >>> infile = open('example.txt', 'r') >>> infile = open('example.txt', 't') >>> infile = open('example.txt') These are all equivalent

  5. Introduction to Computing Using Python File methods There are several file types; they all support similar file methods Methods read() and readline() return the characters read as a string Methods readlines() returns the characters read as a list of lines Method write() returns the number of characters written Usage infile.read(n) Description Read n characters starting from cursor; if fewer than n characters remain, read until the end of file infile.read() infile.readline() Read starting from cursor up to the end of the file Read starting from cursor up to, and including, the end of line character infile.readlines() Read starting from cursor up to the end of the file and return list of lines Write string s to file outfile starting from cursor Close file infile outfile.write(s) infile.close(n)

  6. The file object atrributes: Once a file is opened and you have one file object, you can get various information related to that file. Here is a list of all attributes related to file object: Attribute file.closed Description Returns true if file is closed, false otherwise. file.mode Returns access mode with which file was opened. file.name Returns name of the file. file.softspace Returns false if space explicitly required with print, true otherwise.

  7. Introduction to Computing Using Python Reading a file 1 The 3 lines in this file end with the new line character.\n 2 \n 3 There is a blank line above this line.\n example.txt When the file is opened, a cursor is associated with the opened file >>> infile = open('example.txt') >>> >>> infile.read(1) 'T' >>> >>> infile.read(5) 'he 3 ' >>> >>> infile.readline() 'lines in this file end with the new line character.\n' >>> >>> infile.read() '\nThere is a blank line above this line.\n' >>> >>> infile.close() >>> >>> infile = open('example.txt') >>> infile = open('example.txt') >>> infile.read(1) 'T' 'T' >>> infile.read(5) 'he 3 ' 'he 3 ' >>> infile.readline() 'lines in this file end with the new line character.\n' character.\n' >>> infile.read() '\nThere is a blank line above this line.\n' >>> infile = open('example.txt') >>> infile.read(1) >>> infile.read(1) 'T' >>> infile.read(5) >>> infile.read(5) 'he 3 ' >>> infile.readline() 'lines in this file end with the new line >>> infile = open('example.txt') >>> infile = open('example.txt') >>> infile.read(1) 'T' The initial position of the cursor is: at the beginning of the file, if file mode is r at the end of the file, if file mode is a or w

  8. Introduction to Computing Using Python Patterns for reading a text file Common patterns for reading a file: 1. Read the file content into a string 2. Read the file content into a list of words 3. Read the file content into a list of lines Example: def numChars(filename): 'returns the number of characters in file filename' 'returns the number of words in file filename' 'returns the number of lines in file filename' def numWords(filename): def numLines(filename): infile = open(filename, 'r') content = infile.read() infile.close() infile.close() wordList = content.split() return len(lineList) infile = open(filename, 'r ) infile = open(filename) content = infile.read() lineList = infile.readlines() infile.close() return len(content) return len(wordList)

  9. Introduction to Computing Using Python Writing to a text file 1 T 2 3 3 3 3 3 Non string value like 5 must be converted first.\n 3 Non string value like 5 must be converted first.\n 1 This is the first line. 2 2 2 Now we are in the second line.\n 2 Now we are in the second line.\n 2 Now we are in the second line.\n 1This is the first line. Still the first line \n 1This is the first line. Still the first line \n 1This is the first line. Still the first line \n 1This is the first line. Still the first line \n 1 2 3 4 4 4 4 4 4 4 Non string value like 5 must be converted first.\n test.txt >>> outfile = open('test.txt', 'w') >>> >>> outfile.write('T') 1 >>> >>> outfile.write('his is the first line.') 22 >>> >>> outfile.write(' Still the first line...\n') 25 >>> >>> outfile.write('Now we are in the second line.\n') 31 >>> >>> outfile.write('Non string value like '+str(5)+' must be converted first.\n') 49 >>> >>> outfile.write('Non string value like {} must be converted first.\n'.format(5)) 49 >>> outfile.close() >>> outfile = open('test.txt', 'w') >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 1 >>> outfile.write('his is the first line.') 22 22 >>> outfile.write(' Still the first line...\n') 25 25 >>> outfile.write('Now we are in the second line.\n') 31 31 >>> outfile.write('Non string value like '+str(5)+' must be converted first.\n') 49 >>> outfile = open('test.txt', 'w') >>> outfile.write('T') >>> outfile.write('T') 1 >>> outfile.write('his is the first line.') >>> outfile.write('his is the first line.') 22 >>> outfile.write(' Still the first line...\n') >>> outfile.write(' Still the first line...\n') 25 >>> outfile.write('Now we are in the second line.\n') >>> outfile = open('test.txt', 'w') >>> outfile = open('test.txt', 'w') >>> outfile.write('T') 1 1 >>> outfile.write('his is the first line.') 22 >>> outfile = open('test.txt', 'w') >>> outfile.write('T')

  10. A list of the different modes of opening a file: Modes Description r Opens a text file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. Opens a file for both reading and writing. The file pointer will be at the beginning of the file. Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file. Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. rb r+ rb+ w wb w+

  11. A list of the different modes of opening a file: wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Related


More Related Content