KEMBAR78
FILE INPUT OUTPUT.pptx
File Input Output
Accessing Keyboard Input: raw_input
and input
 The input() function allows user input. Whatever you enter as input, the input
function converts it into a string.
 That means we are able to ask the user for input using input() function.
 The method is a bit different in Python 3.6 than Python 2.7.
 Python 3.x onwards, it uses the input() method.
 Python 2.x used the raw_input() method.
Printing to the Screen: print()
 The print() function prints the specified message to the
screen, or other standard output device.
 The message can be a string, or any other object,
the object will be converted into a string before written
to the screen.
Syntax
 print(object(s), sep=separator, end=end,
file=file, flush=flush)
object(s) Any object, and as many as
you like. Will be converted to
string before printed
sep='separator' Optional. Specify how to
separate the objects, if there
is more than one. Default is ' '
end='end' Optional. Specify what to
print at the end. Default is 'n'
(line feed)
file Optional. An object with a
write method. Default is
sys.stdout
flush Optional. A Boolean,
specifying if the output is
flushed (True) or buffered
(False). Default is False
File Handling
 The key function for working with files in Python is the open() function.
 The open() function takes two parameters; filename, and mode.
 There are a number of different methods (modes) for opening a file
 In addition you can specify if the file should be handled as binary or text
mode
 "t" - Text - Default value. Text mode
 "b" - Binary - Binary mode (e.g. images)
 Syntax
 To open a file for reading it is enough to specify the name of the file:
 f = open("demofile.txt")
 The code above is the same as:
 f = open("demofile.txt", "rt")
 Because "r" for read, and "t" for text are the default values, you do not need to
specify them.
 Note: Make sure the file exists, or else you will get an error.
File modes
 The following modes are supported:
 x: Create - will create a file, returns an error if the file exist
 r : Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
 rb: 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.
 r+ : Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
 rb+: Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.
 w : 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.
 wb: 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.
 w+: 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.
 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.
read functions: read(), readline(),
readlines()
 The read() method returns the specified number of bytes from the file. Default is -1 which means
the whole file.
 Python readline() method will return a line from the file when called.
 readlines() method will return all the lines in a file in the format of a list
where each element is a line in the file.
 file = open("filename.txt", "r")
file.readline()
 file = open("filename.txt","r")
file.readlines()
Python File Write
 Write to an Existing File
 To write to an existing file, you must add a parameter to the open() function:
 "a" - Append - will append to the end of the file
 "w" - Write - will overwrite any existing content
 Example
 Open the file "demofile2.txt" and append content to the file:
 f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
 The write() function will write the content in the file without adding any
extra characters.
 writelines() function
 This function writes the content of a list to a file.
 As per the syntax, the list of strings that is passed to the writelines() function
is written into the opened file. Similar to the write() function, the
writelines() function does not add a newline character(n) to the end of the
string.
file1 = open("Employees.txt", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + 'n’)
file1.writelines(lst)
file1.close()
print("Data is written into the file.")
 The only difference between the write() and writelines() is that write() is used to
write a string to an already opened file while writelines() method is used to write
a list of strings in an opened file.
Close files
 It is a good practice to always close the file when you are done with
it.
 Example
 Close the file when you are finish with it:
 f = open("demofile.txt", "r")
print(f.readline())
f.close()
 Note: You should always close your files, in some cases, due to
buffering, changes made to a file may not show until you close the
file.
Other file operations
 open()
 close()
 tell()
 seek()
 flush()
 fileno()
 isatty()
 next()
Redirecting Output Streams To a File
 import sys
 restorePoint = sys.stdout
 sys.stdout = open(‘files.txt’,’a’)
 print(‘This is Python’)
 print(‘Python is great’)
 print(‘I love Python’)
 sys.stdout = restorePoint
 print(‘End of program’)

FILE INPUT OUTPUT.pptx

  • 1.
  • 2.
    Accessing Keyboard Input:raw_input and input  The input() function allows user input. Whatever you enter as input, the input function converts it into a string.  That means we are able to ask the user for input using input() function.  The method is a bit different in Python 3.6 than Python 2.7.  Python 3.x onwards, it uses the input() method.  Python 2.x used the raw_input() method.
  • 3.
    Printing to theScreen: print()  The print() function prints the specified message to the screen, or other standard output device.  The message can be a string, or any other object, the object will be converted into a string before written to the screen. Syntax  print(object(s), sep=separator, end=end, file=file, flush=flush) object(s) Any object, and as many as you like. Will be converted to string before printed sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default is ' ' end='end' Optional. Specify what to print at the end. Default is 'n' (line feed) file Optional. An object with a write method. Default is sys.stdout flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False
  • 4.
    File Handling  Thekey function for working with files in Python is the open() function.  The open() function takes two parameters; filename, and mode.  There are a number of different methods (modes) for opening a file  In addition you can specify if the file should be handled as binary or text mode  "t" - Text - Default value. Text mode  "b" - Binary - Binary mode (e.g. images)
  • 5.
     Syntax  Toopen a file for reading it is enough to specify the name of the file:  f = open("demofile.txt")  The code above is the same as:  f = open("demofile.txt", "rt")  Because "r" for read, and "t" for text are the default values, you do not need to specify them.  Note: Make sure the file exists, or else you will get an error.
  • 6.
    File modes  Thefollowing modes are supported:  x: Create - will create a file, returns an error if the file exist  r : Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.  rb: 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.  r+ : Opens a file for both reading and writing. The file pointer placed at the beginning of the file.  rb+: Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.  w : 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.  wb: 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.
  • 7.
     w+: Opensa 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.  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.
  • 8.
    read functions: read(),readline(), readlines()  The read() method returns the specified number of bytes from the file. Default is -1 which means the whole file.  Python readline() method will return a line from the file when called.  readlines() method will return all the lines in a file in the format of a list where each element is a line in the file.  file = open("filename.txt", "r") file.readline()  file = open("filename.txt","r") file.readlines()
  • 9.
    Python File Write Write to an Existing File  To write to an existing file, you must add a parameter to the open() function:  "a" - Append - will append to the end of the file  "w" - Write - will overwrite any existing content  Example  Open the file "demofile2.txt" and append content to the file:  f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close() #open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read())
  • 10.
     The write()function will write the content in the file without adding any extra characters.  writelines() function  This function writes the content of a list to a file.  As per the syntax, the list of strings that is passed to the writelines() function is written into the opened file. Similar to the write() function, the writelines() function does not add a newline character(n) to the end of the string.
  • 11.
    file1 = open("Employees.txt","w") lst = [] for i in range(3): name = input("Enter the name of the employee: ") lst.append(name + 'n’) file1.writelines(lst) file1.close() print("Data is written into the file.")  The only difference between the write() and writelines() is that write() is used to write a string to an already opened file while writelines() method is used to write a list of strings in an opened file.
  • 12.
    Close files  Itis a good practice to always close the file when you are done with it.  Example  Close the file when you are finish with it:  f = open("demofile.txt", "r") print(f.readline()) f.close()  Note: You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.
  • 13.
    Other file operations open()  close()  tell()  seek()  flush()  fileno()  isatty()  next()
  • 14.
    Redirecting Output StreamsTo a File  import sys  restorePoint = sys.stdout  sys.stdout = open(‘files.txt’,’a’)  print(‘This is Python’)  print(‘Python is great’)  print(‘I love Python’)  sys.stdout = restorePoint  print(‘End of program’)