YouTip LogoYouTip

Python Files Io

## Python2.x Python File I/O\n\nThis chapter only covers all basic I/O functions. For more functions, please refer to the Python standard documentation.\n\n## Print to Screen\n\nThe simplest way to output is to use the print statement, which can accept zero or more expressions separated by commas. This function converts the expressions you pass into a string expression and writes the result to standard output as follows:\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nprint "Python It's a great language, isn't it?"\n\nThe following result will be displayed on your standard screen:\n\nPython It's a great language, isn't it?\n\n## Reading Keyboard Input\n\nPython provides two built-in functions to read a line of text from standard input, where the default standard input is the keyboard. They are as follows:\n\n* raw_input\n* input\n\n### raw_input Function\n\nThe raw_input() function reads a line from standard input and returns a string (with the trailing newline removed):\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nstr = raw_input("Please enter:")\nprint "Your input is: ", str\n\nThis will prompt you to enter any string, and then display the same string on the screen. When I enter "Hello Python!", its output is as follows:\n\nPlease enter: Hello Python!\nYour input is: Hello Python!\n\n### input Function\n\nThe **input()** function is basically similar to **raw_input()**, but input can accept a Python expression as input and return the calculated result.\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nstr = input("Please enter:")\nprint "Your input is: ", str\n\nThis will produce the following result corresponding to the input:\n\nPlease enter:[x*5 for x in range(2,10,2)]\nYour input is: [10, 20, 30, 40]\n\n## Opening and Closing Files\n\nNow, you can already read and write to standard input and output. Now, let's look at how to read and write actual data files.\n\nPython provides the necessary functions and methods for basic file operations under default circumstances. You can use the **file** object to perform most file operations.\n\n### open Function\n\nYou must first use Python's built-in open() function to open a file and create a file object before you can call its related methods for reading and writing.\n\nSyntax:\n\nfile object = open(file_name [, access_mode][, buffering])\n\nThe details of each parameter are as follows:\n\n* file_name: The file_name variable is a string value containing the name of the file you want to access.\n* access_mode: The access_mode determines the mode in which the file is opened: read-only, write, append, etc. All allowable values are listed in the complete list below. This parameter is optional, and the default file access mode is read-only (r).\n* buffering: If the buffering value is set to 0, there will be no buffering. If the buffering value is 1, lines will be buffered when accessing the file. If the buffering value is set to an integer greater than 1, the size of the buffer for the buffering area is indicated. If a negative value is used, the buffer size will be the system default.\n\nComplete list of modes for opening files:\n\n| Mode | Description |\n| --- | --- |\n| t | Text mode (default). |\n| x | Write mode, creates a new file, raises an error if the file already exists. |\n| b | Binary mode. |\n| + | Opens a file for update (read and write). |\n| U | Universal newline mode (not recommended). |\n| r | Opens a file for reading only. The file pointer will be placed at the beginning of the file. This is the default mode. |\n| rb | Opens a file for reading only in binary format. The file pointer will be placed at the beginning of the file. This is the default mode. Usually used for non-text files such as images. |\n| r+ | Opens a file for reading and writing. The file pointer will be placed at the beginning of the file. |\n| rb+ | Opens a file for reading and writing in binary format. The file pointer will be placed at the beginning of the file. Usually used for non-text files such as images. |\n| w | Opens a file for writing only. If the file already exists, it opens the file and starts editing from the beginning, meaning the original content will be deleted. If the file does not exist, creates a new file. |\n| wb | Opens a file for writing only in binary format. If the file already exists, it opens the file and starts editing from the beginning, meaning the original content will be deleted. If the file does not exist, creates a new file. Usually used for non-text files such as images. |\n| w+ | Opens a file for reading and writing. If the file already exists, it opens the file and starts editing from the beginning, meaning the original content will be deleted. If the file does not exist, creates a new file. |\n| wb+ | Opens a file for reading and writing in binary format. If the file already exists, it opens the file and starts editing from the beginning, meaning the original content will be deleted. If the file does not exist, creates a new file. Usually used for non-text files such as images. |\n| a | Opens a file for appending. If the file already exists, the file pointer will be at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, creates a new file for writing. |\n| ab | Opens a file for appending in binary format. If the file already exists, the file pointer will be at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, creates a new file for writing. |\n| a+ | Opens a file for reading and writing. If the file already exists, the file pointer will be at the end of the file. The file will be opened in append mode when opened. If the file does not exist, creates a new file for reading and writing. |\n| ab+ | Opens a file for appending in binary format. If the file already exists, the file pointer will be at the end of the file. If the file does not exist, creates a new file for reading and writing. |\n\nThe following image summarizes these modes well:\n\n!(#)\n\n| Mode | r | r+ | w | w+ | a | a+ |\n| --- | --- | --- | --- | --- | --- | --- |\n| Read | + | + | | + | | + |\n| Write | | + | + | + | + | + |\n| Create | | | + | + | + | + |\n| Overwrite | | | + | + | | |\n| Pointer at start | + | + | + | + | | |\n| Pointer at end | | | | | + | + |\n\n## File Object Attributes\n\nAfter a file is opened, you have a file object, and you can get various information about the file.\n\nThe following is a list of all attributes related to the file object:\n\n| Attribute | Description |\n| --- | --- |\n| file.closed | Returns true if the file has been closed, otherwise returns false. |\n| file.mode | Returns the access mode of the opened file. |\n| file.name | Returns the name of the file. |\n| file.softspace | Returns false if a space character must be followed after print output. Otherwise returns true. |\n\nExample as follows:\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n# Open a file\nfo = open("foo.txt", "w")\nprint "Filename: ", fo.name\nprint "Is closed? : ", fo.closed\nprint "Access mode : ", fo.mode\nprint "Is a trailing space mandatory? : ", fo.softspace\n\nThe output of the above example is:\n\nFilename: foo.txt\nIs closed? : False\nAccess mode : w\nIs a trailing space mandatory? : 0\n\n### close() Method\n\nThe close() method of the File object flushes any unwritten information in the buffer and closes the file, after which no further writing can be done.\n\nWhen a file object's reference is reassigned to another file, Python will close the previous file. It is a good habit to close files using the close() method.\n\nSyntax:\n\nfileObject.close()\n\nExample:\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n# Open a file\nfo = open("foo.txt", "w")\nprint "Filename: ", fo.name\n# Close the opened file\nfo.close()\n\nThe output of the above example is:\n\nFilename: foo.txt\n\nReading and Writing Files:\n\nThe file object provides a series of methods that can make our file access easier. Let's look at how to use the read() and write() methods to read from and write to files.\n\n### write() Method\n\nThe write() method can write any string to an open file. It is important to note that Python strings can be binary data, not just text.\n\nThe write() method does not add a newline character ('n') at the end of the string:\n\nSyntax:\n\nfileObject.write(string)\n\nHere, the parameter passed is the content to be written to the opened file.\n\nExample:\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n# Open a file\nfo = open("foo.txt", "w")\nfo.write( "www..com!nVery good site!n" )\n# Close the opened file\nfo.close()\n\nThe above method will create the foo.txt file and write the received content to the file, and finally close the file. If you open this file, you will see the following:\n\n$ cat foo.txt\nwww..com!\nVery good site!\n\n### read() Method\n\nThe read() method reads a string from an open file. It is important to note that Python strings can be binary data, not just text.\n\nSyntax:\n\nfileObject.read()\n\nHere, the parameter passed is the number of bytes to read from the opened file. This method reads from the beginning of the file. If count is not passed, it tries to read as much as possible, likely until the end of the file.\n\n### Example:\n\nHere we use the foo.txt file created above.\n\n## Example\n\n#!/usr/bin/python\n\n# -*- coding: UTF-8 -*-\n\n# Open a file\n\n fo =open("foo.txt","r+")\n\nstr= fo.read(10)\n\nprint"The read string is : ",str\n\n# Close the opened file\n\n fo.close()\n\nThe output of the above example is:\n\nThe read string is : www.\n\n* * *\n\n## File Positioning\n\nThe tell() method tells you the current position within the file. In other words, the next read or write will occur after that many bytes from the beginning of the file.\n\nThe seek(offset [,from]) method changes the current file position. The offset variable indicates the number of bytes to move. The from variable specifies the reference position from which to start moving bytes.\n\nIf from is set to 0, it means the beginning of the file is used as the reference position for moving bytes. If set to 1, the current position is used as the reference. If set to 2, the end of the file will be used as the reference position.\n\nExample:\n\nWe'll use the foo.txt file we created above.\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n# Open a file\nfo = open("foo.txt", "r+")\nstr = fo.read(10)\nprint "The read string is : ", str\n# Get current position\nposition = fo.tell()\nprint "Current file position : ", position\n# Reset the pointer to the beginning of the file\nposition = fo.seek(0, 0)\nstr = fo.read(10)\nprint "Read the string again : ", str\n# Close the opened file\nfo.close()\n\nThe output of the above example is:\n\nThe read string is : www.\nCurrent file position : 10\nRead the string again : www.\n\n## Renaming and Deleting Files\n\nPython's os module provides methods to help you perform file processing operations, such as renaming and deleting files.\n\nTo use this module, you must first import it before you can call its related functions.\n\n### rename() Method\n\nThe rename() method requires two parameters: the current filename and the new filename.\n\nSyntax:\n\nos.rename(current_file_name, new_file_name)\n\nExample:\n\nThe following will rename an existing file test1.txt.\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport os\n# Rename file test1.txtTo test2.txt。\nos.rename( "test1.txt", "test2.txt" )\n\n### remove() Method\n\nYou can use the remove() method to delete files, providing the filename to be deleted as a parameter.\n\nSyntax:\n\nos.remove(file_name)\n\nExample:\n\nThe following will delete an existing file test2.txt.\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport os\n# Delete an existing file test2.txt\nos.remove("test2.txt")\n\nAll files are contained in different directories, but Python can also handle them easily. The os module has many methods to help you create, delete, and change directories.\n\n### mkdir() Method\n\nYou can use the os module's mkdir() method to create new directories under the current directory. You need to provide a parameter containing the name of the directory to be created.\n\nSyntax:\n\nos.mkdir("newdir")\n\nExample:\n\nThe following will create a new directory test under the current directory.\n\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport os\n# Create directory test\nos.mkdir("test")\n\n### chdir() Method\n\nYou can use the chdir() method to change the current directory. The chdir() method
← Python ExceptionsProp Webcontrol Xml Documentso β†’