Python File Modes<\/strong><\/p>\nPython has defined file modes that can be implemented when a file is opened. These modes define what can be done with the file once it is opened. If you do not mention the mode then \u201cread\u201d is considered the default mode. The list of various modes is given as follows:<\/p>\n
\u2018r\u2019 is also the default mode, it means that the file has been opened for reading purposes. You have already seen the usage of reading mode. To explain this a file by the name \u201ctest.txt\u201d has been created. The content of the file is as follows:<\/p>\n
\u201cI am excited about writing on the file using Python for the first time. Hope You feel the same. \u201d<\/p>\n
We will now give the following commands.:<\/p>\n
>>> f_handle = open(\"test.txt\" , 'r')\r\n>>> f_handle . read (4)<\/pre>\nThe output for the above code is :
\n\u2018I am\u2019<\/p>\n
f_handle.read(4)<\/strong> retrieves the first four characters from the file and displays it.<\/p>\n\u2018w\u2019 stands for writing. It means that you want to open a file and write in it. In case the file that you have mentioned does not exist then a new file will be created.<\/p>\n
>>> f_handle = open(\"test .txt\",'w')\r\n>>> f_handle.write(\"I am excited about writing on the file using Python for the first time.\")\r\n71\r\n>>> f_handle.write(\"Hope you feel the same.\")\r\n22\r\n>>> f_handle.close( )\r\n>>><\/pre>\nSo, if you open the file now this is how the contents would look like:<\/p>\n
The original content of the file before passing the write instructions was:\r\n\u201cI am excited about writing on the file using Python for the first time. Hope you feel the same.\u201d\r\nIf you open the file after passing \u201cwrite\u201d instructions now the contents of the file will be as follows:\r\n\u201cHi I have opened this file again and I feel great again. \u201d<\/pre>\nAs you can see that the previous lines (\/ am excited about writing on the file using Python for the first time. Hope you feel the same.) have been erased from the file.<\/p>\n
Now, we close the file and try to write something again in it.<\/p>\n
>>> f_handle = open (test. txt\", ' w' )\r\n>>> f_handle.write (\"\\n Hi I have opened this file again and I feel great again.\")\r\n58\r\n>>> f_handle.close ( )\r\n>>><\/pre>\n\u2018x\u2019 stands for exclusive creation. An error will be displayed if the file already exists. Let\u2019s see what happens when we try to use \u2018x\u2019 mode with an already existing test.txt<\/strong> file.<\/p>\n>>> f_handle = open(\"F:\/test.txt\"x')\r\nTraceback (most recent call last):\r\n File \"<pyshell#l>\", line 1, in <module>\r\nf_handle = open(\"F:\/test.txt\"x')\r\nFileExistsError: [Errno 17] File exists: 'F:\/test.txt'<\/pre>\n\u2018a\u2019 is used to append an existing file. If a file does not exist then a new file will be created.<\/p>\n
So, now we try to add new text to an already existing file.<\/p>\n
The contest of test.txt<\/strong> file is as follows:<\/p>\n\u201cI am excited about writing on the file using Python for the first time.\r\nHope You feel the same. \u201d<\/pre>\nWe will try to add the following line to it:<\/p>\n
\u201cHi I have opened this file again and I feel great again. \u201d<\/pre>\nIn order to append, we follow the following steps:<\/p>\n
>>> f_handle = open(\"test.txt\",'a')\r\n>>> f_handle.write(\"Hi I have opened this file again and I feel great again.\")\r\n56\r\n>>> f_handle.close()\r\n>>><\/pre>\nOutput<\/strong><\/p>\nI am excited about writing on the file using Python for the first time.\r\nHope You feel the same.\r\n\r\n\r\nHi, I have opened this file again and I feel great again.<\/pre>\n\u2018t\u2019 is used to open a file in text mode and \u2018b\u2019 is used to open the file in binary mode.<\/p>\n
In the above examples, you must have noticed f_handle.close( )<\/strong> command. It is important to use the close( )<\/strong> command after you have stopped working with a file in order to free up operating system resources. If you leave the file open, you may encounter problems.<\/p>\nA better way of dealing with files is to keep the code related to file reading in a try block as shown in the following code:<\/p>\n
>>> try:\r\n f_handle = open (\"llllearning_files . txt\")\r\n content = f_handle.read()\r\n f_handle.close()\r\nexcept for IOError:\r\n print (''Could not find the file. Please check again\")\r\n exit( )<\/pre>\nOutput<\/strong><\/p>\nCould not find the file. Please check again<\/pre>\nIn the above piece of code, the file name given does not exist in the given location. Hence, the remaining code of the try block is ignored and the code written in the except block is applied. In the except block, we have provided a simpler and user-friendly message which is easier for the user to understand. Without the try expect to block the following message will be displayed:<\/p>\n
Traceback (most recent call last):\r\n File \"<pyshell#10>\", line 1, in <module>\r\n f_handle = open (\"llllearning_files .txt\")\r\nFileNotFoundError: [Errno 2] No such file or\r\ndirectory: 'llllearning_files . txt'<\/pre>\nWhich can be difficult to decipher.<\/p>\n
File-system-type commands:<\/strong><\/p>\nNow we will have a look at some very common file-system-type operations such as move, copy, and so on.
\nWe now try to copy the contents of this file to another file. For this we require to import shutil<\/strong> as shown in the following code:<\/p>\n>>> import shutil\r\n>>> shutil. copy(\"F:\/test.txt\",\"F:\/testl.txt\")\r\n'F:\/testl.txt'<\/pre>\nOutput<\/strong><\/p>\nContent of testl.txt file:<\/strong><\/p>\nYou can move the file or change the name of the file using the move command as shown in the following code:<\/p>\n
>>> import shutil\r\n>>> shutil.move(\"test.txt\",\"test2.txt\")\r\n'test2.txt'\r\n>>><\/pre>\nThe above set of instructions changes the name of the file test.txt<\/strong> to test2. txt<\/strong>.<\/p>\nAnother important package available with Python is glob<\/strong>.<\/p>\nThe glob package allows you to create a list of a particular type of files by using the star * operator.<\/p>\n
>>> import glob\r\n>>> glob.glob(\"*.txt\")\r\n['important.txt', 'learning_files.txt', ' test1. txt', 'test2.txt']\r\n>>><\/pre>\nQuestion 1.
\nHow is a file opened for reading? Provide an example.
\nAnswer:
\nUsing the open function, and the ‘r’ mode.
\nmyFile = openCpathToFile’,’r’)<\/p>\n
Question 2.
\nWhat is the appropriate method to call when a file is no longer being used?
\nAnswer:
\nfile.close( )<\/p>\n
Question 3.
\nWhat are the modes that a file can be opened in? Answer:<\/p>\n
\n- ‘r’ – reading,<\/li>\n
- ‘w’ – writing,<\/li>\n
- ‘a’ – append,<\/li>\n
- ‘r+’ reading and writing, contents intact,<\/li>\n
- ‘w+’ reading and writing, contents deleted,<\/li>\n
- ‘a+’ same as ‘r+’<\/li>\n<\/ul>\n
Question 4.
\nWhat does the ‘b’ modifier do when appended to a file mode?
\nAnswer:
\nIt changes the handling of the file from text to binary mode.<\/p>\n
Question 5.
\nWhat does the ‘U’ modifier do when appended to a file mode?
\nAnswer:
\nIt applies the universal new-line translator to the file when it is opened.<\/p>\n
Question 6.
\nHow is the buffer size specified in the file opening?
\nAnswer:
\nIt is an optional parameter to the open function. A 0 indicates the file is unbuffered, 1 indicates that line by line buffering. Any other positive number is the actual buffer size to be allocated.<\/p>\n
Question 7.
\nHow is an entire file read into a buffer and returned as a string? When is it a bad practice to do so?
\nAnswer:
\nWith the .read( ) method. When the file may be large, because the buffer may consume excessive memory.<\/p>\n
Question 8.
\nHow is a file read using a limited buffer size?
\nAnswer:
\nBy specifying how many bytes to read in the read method. file.read(20) would read the next 20 bytes from the file.<\/p>\n
Question 9.
\nHow can a single line be read from a text file? Provide an illustration.
\nAnswer:
\nUsing the linecache module.
\nimport linecache
\nmyFile = \u201c’file.txt”
\nprint linecache.getline(myFile, 1) # prints the first line
\nprint linecache.getline(myFile,40) # prints the 40th line, etc.<\/p>\n
Question 10.
\nWhat are two ways to write a line of text to a file?
\nAnswer:
\nUsing the .write method on an open file, or >>> redirection operator to use the print statement.<\/p>\n
Question 11.
\nWith a list of strings, how can they all be written out to a file in a single statement?
\nAnswer:
\nUsing the .writelines( ) method. Example:
\nmyFile.writelinesdistName)<\/p>\n
Question 12.
\nIllustrate how to determine the number of lines in a text file, using the readlines method. When would it be inappropriate to use this technique?
\nAnswer:
\nmyLineCount = len(open(myFilePath, Y).readlines())
\nIt would be inappropriate to use if the file might be large, because the readlines method will generate a list of strings that includes the entire file’s contents. It would consume too much memory.<\/p>\n
Question 13.
\nWhat module and method is used to traverse the file system directory tree?
\nAnswer:
\nThe os module. Specifically os.walk.<\/p>\n
Question 14.
\nHow are files deleted?
\nAnswer:
\nUsing the os.remove method. os.remove(‘myFile\u2019)<\/p>\n
Question 15.
\nHow are files renamed?
\nAnswer:
\nUsing the os.rename method. os.renameColdFileName’, \u2018newFileName’)<\/p>\n
Question 16.
\nHow are entire non-empty directory trees removed?
\nAnswer:
\nEach directory must be walked using the os.walk method, then the files within must be deleted. Then and only then can the directory be removed using the os.rmdir method.<\/p>\n
Question 17.
\nHow is a tarfile created?
\nAnswer:
\nUsing the tarfile module.
\nimport tarfile
\nmy Tar = tarfile.open(“my Tarfile”, ‘w’)<\/p>\n
Question 18.
\nHow are files added to a tarfile or zipfile?
\nAnswer:
\nUsing the .add method to an open tar or zip file.<\/p>\n
Question 19.
\nHow are files extracted from a tar or zip file?
\nAnswer:
\nUsing the .extract method on an open tar or zip file, and specifying the file name and the extraction path.<\/p>\n
Question 20.
\nIllustrate extracting all of the .txt files from a zip file.
\nAnswer:
\nimport os
\nimport zipfile
\nmyZip = zipfile.open(“myZip.zip “, Y)
\nfor myFile in myZip.getnames( ):
\nif myFile.endswith(\u201ctxt”):
\nmyZip.extract(myFile, “-\/temp\/”)
\nmyZip.close( )<\/p>\n","protected":false},"excerpt":{"rendered":"
We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels. Python Interview Questions on File Manipulation Till now you have learned how to implement logic in Python to write blocks of code that can help you accomplish certain tasks. In this section, we will learn about how to …<\/p>\n
Python Interview Questions on File Manipulation<\/span> Read More »<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[5],"tags":[],"yoast_head":"\nPython Interview Questions on File Manipulation - Python Programs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n