{"id":10060,"date":"2023-11-05T11:11:15","date_gmt":"2023-11-05T05:41:15","guid":{"rendered":"https:\/\/python-programs.com\/?p=10060"},"modified":"2023-11-10T12:18:15","modified_gmt":"2023-11-10T06:48:15","slug":"python-interview-questions-on-file-manipulation","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-interview-questions-on-file-manipulation\/","title":{"rendered":"Python Interview Questions on File Manipulation"},"content":{"rendered":"

We have compiled most frequently asked Python Interview Questions<\/a> which will help you with different expertise levels.<\/p>\n

Python Interview Questions on File Manipulation<\/h2>\n

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 use Python to work with files. You can read data from files and you can also write data to the files. You can not only access the internet but also check your emails and social media accounts using the Python programming language.<\/p>\n

Files<\/strong><\/p>\n

A file has a permanent location. It exists somewhere on the computer disk and can be referred to anytime. It is stored on the hard disk in non-volatile memory which means the information in the file remains even if the computer is switched off. In this section, we will learn how to deal with files in Python.<\/p>\n

Open a File<\/strong><\/p>\n

If you want to work on an existing file, then you will have to first open the file. In this section, we will learn how to open a file.
\nIn order to open a file, we will make use of the open( )<\/strong> function which is an inbuilt function. When we use the open( )<\/strong> function, a file object is returned which can be used to read or modify the file. If the file exists in the same directory where python is installed then you need not give the entire pathname. However, if the location is different then you will have to mention the entire path.<\/p>\n

For this example, I have created a file by the name: learning_files.txt<\/strong> in the current directory of python \/home\/pi.<\/strong><\/p>\n

The content of the file is as follows:<\/p>\n

I am great a learning files<\/strong><\/p>\n

See how Good I am at opening Files<\/strong><\/p>\n

Thank you Python<\/strong><\/p>\n

Look at the following piece of code:<\/p>\n

>>> f_handle = open (\"learning_files . txt\")\r\n>>> print (f_handle . read ( ) )<\/pre>\n

In case the file is not available, the error message will be displayed as follows:<\/p>\n

>>> f_handle = open (\"llllearning_files . txt\")\r\nTraceback (most recent call last):\r\n   File \"<pyshell#0>\", 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'\r\n>>><\/pre>\n

Output<\/strong><\/p>\n

I am great a learning files\r\nSee how Good I am at opening Files\r\nThank you Python<\/pre>\n

Python File Modes<\/strong><\/p>\n

Python 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>\n

The 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>\n

So, 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>\n

As 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>\n

We 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>\n

In 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>\n

Output<\/strong><\/p>\n

I 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>\n

A 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>\n

Output<\/strong><\/p>\n

Could not find the file. Please check again<\/pre>\n

In 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>\n

Which can be difficult to decipher.<\/p>\n

File-system-type commands:<\/strong><\/p>\n

Now 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>\n

Output<\/strong><\/p>\n

Content of testl.txt file:<\/strong><\/p>\n

You 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>\n

The above set of instructions changes the name of the file test.txt<\/strong> to test2. txt<\/strong>.<\/p>\n

Another important package available with Python is glob<\/strong>.<\/p>\n

The 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>\n

Question 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