Auto AdSense

Saturday, 24 January 2015

Python Files I/O






  • Reading Keyboard Input:
    Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are:
    raw_input
    input
    • The raw_input Function:
      #!/usr/bin/python

      str = raw_input("Enter your input: ");
      print "Received input is : ", str
      Output
      Enter your input: Hello Python
      Received input is : Hello Python
    • The input Function:
      #!/usr/bin/python

      str = input("Enter your input: ");
      print "Received input is : ", str
      Output
      Enter your input: [x*5 for x in range(2,10,2)]
      Recieved input is : [10, 20, 30, 40]
  • Opening and Closing Files:
    Syntax:
    file object = open(file_name [, access_mode][, buffering])

    Here is paramters detail:
    1. file_name: The file_name argument is a string value that contains the name of the file that you want to access.

    2. access_mode: The access_mode determines the mode in which the file has to be opened ie. read, write append etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r)

    3. buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).
  • The file object atrributes:
    #!/usr/bin/python

    # Open a file
    fo = open("foo.txt", "wb")
    print "Name of the file: ", fo.name
    print "Closed or not : ", fo.closed
    print "Opening mode : ", fo.mode
    print "Softspace flag : ", fo.softspace
    Output
    Name of the file: foo.txt
    Closed or not : False
    Opening mode : wb
    Softspace flag : 0
  • The close() Method:
    Syntax:
    fileObject.close();
    #!/usr/bin/python

    # Open a file
    fo = open("foo.txt", "wb")
    print "Name of the file: ", fo.name

    # Close opend file
    fo.close()
    Output
    Name of the file: foo.txt
  • Reading and Writing Files:
    • 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.

      The write() method does not add a newline character ('\n') to the end of the string:
      Syntax:
      fileObject.write(string);

      Here passed parameter is the content to be written into the opend file.
      Example:
      #!/usr/bin/python

      # Open a file
      fo = open("foo.txt", "wb")
      fo.write( "Python is a great language.\nYeah its great!!\n");

      # Close opend file
      fo.close()

      The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content

      Python is a great language.
      Yeah its great!!
    • The read() Method:
      Syntax:
      fileObject.read([count]);
      #!/usr/bin/python

      # Open a file
      fo = open("foo.txt", "r+")
      str = fo.read(10);
      print "Read String is : ", str
      # Close opend file
      fo.close()

      This would produce following result:

      Read String is : Python is
  • File Positions:
    #!/usr/bin/python

    # Open a file
    fo = open("foo.txt", "r+")
    str = fo.read(10);
    print "Read String is : ", str

    # Check current position
    position = fo.tell();
    print "Current file position : ", position

    # Reposition pointer at the beginning once again
    position = fo.seek(0, 0);
    str = fo.read(10);
    print "Again read String is : ", str
    # Close opend file
    fo.close()
    This would produce following result:

    Read String is : Python is
    Current file position : 10
    Again read String is : Python is
  • Renaming and Deleting Files:
    • The rename() Method:
      The rename() method takes two arguments, the current filename and the new filename.
      Syntax:
      os.rename(current_file_name, new_file_name)
      Example:
      Following is the example to rename an existing file test1.txt:

      #!/usr/bin/python
      import os

      # Rename a file from test1.txt to test2.txt
      os.rename( "test1.txt", "test2.txt" )
    • The delete() Method:
      Syntax:
      os.delete(file_name)
      Example:
      Following is the example to delete an existing file test2.txt:

      #!/usr/bin/python
      import os

      # Delete file test2.txt
      os.delete("text2.txt")
  • Directories in Python:
    • The mkdir() Method:
      Syntax:
      os.mkdir("newdir")
      Example:
      Following is the example to create a directory test in the current directory:

      #!/usr/bin/python
      import os

      # Create a directory "test"
      os.mkdir("test")
    • The chdir() Method:
      Syntax:
      os.chdir("newdir")
      Example:
      Following is the example to go into "/home/newdir" directory:

      #!/usr/bin/python
      import os

      # Changing a directory to "/home/newdir"
      os.chdir("/home/newdir")
    • The getcwd() Method:
      Syntax:
      os.getcwd()
      Example:

      Following is the example to give current directory:
      #!/usr/bin/python
      import os

      # This would give location of the current directory
      os.getcwd()
    • The rmdir() Method:
      Syntax:

      os.rmdir('dirname')
      Example:
      Following is the example to remove "/tmp/test" directory. It is required to give fully qualified name of the directory otherwise it would search for that directory in the current directory.

      #!/usr/bin/python
      import os

      # This would remove "/tmp/test" directory.
      os.rmdir( "/tmp/test" )

No comments:

Post a Comment