How to Input File in Python

Posted on

Introduction

This is also another article which is the expansion to describe more detail aspect from a previous article. In the previous article exist in this link with the title of ‘How to Input in Python’, there is some discussion about how to input in Python programming language. One of the input type or format is file input. So, in this article, the focus will be on how to input file in Python programming language.

How to Input File in Python

Before going on further into detail, the following is the default pattern or syntax to handle input file in Python programming language. Definitely, the default pattern or syntax to handle input file exist as in the following script or snippet code :

open('file_name.file_extension');

As for the example of the execution for retrieving file as an input, it is actually exist below :

C:\python>python
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> text_content = open('text_file.txt');
>>> print(text_content);
<_io.TextIOWrapper name='text_file.txt' mode='r' encoding='cp1252'>
>>> quit()

Before going on to the detail explanation, below is the location of the ‘text_file.txt’ file which is a text file as a source file for retrieving the file exist in the following location :

C:\python>dir
Volume in drive C is Windows-SSD
Volume Serial Number is CA30-19A4

Directory of C:\python

08/17/2022 05:35 PM <DIR> .
08/17/2022 11:04 AM <DIR> ..
08/17/2022 05:36 PM 125 text_file.txt
1 File(s) 61,768 bytes
2 Dir(s) 86,667,075,584 bytes free

C:\python>

So, the execution of the python command console is in the path of ‘C:\python’. Furthermore, the location of the file which is going to fulfill the role as the input source is also in the same folder. It exist in ‘C:\python’. That is a text file with the name of ‘text_file.txt’. In the above execution, it just print the variable with the name of ‘text_content’. Apparently, it does not print the content of the text file, but it is print the type of the object which is a text file. Basically, as another information, by default, open() method as a method to retrieve file input is using ‘read’ mode.

One thought on “How to Input File in Python

Leave a Reply