Files in Python

 Files?

Python uses file objects to interact with external files which are available on you location computer and the files can be any sort of file like, Text file, audio file, excel file, and even Emails.

Creating a File:

If you are using Windows create a text file based on the location (if you are using command line method). However, if you are using Jupyter notebook you could use below command to create a text file.

%%writefile firstfile.txt 
This is my first text file to run the python commands.
I will execute this file to test the result.
It is the end of the text file.


Open a File:

>>> mytextfile=open('first_file.txt')

Note: If your file is not at a default location so you will get the below error (if file doesn't exists) 

>>> mytextfile=open('first_file1.txt')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'first_file1.txt'

The above error explains that, either the files doesn't exist or the file name is not correct.

If you want to open a file from a specific folder or directory, use below command:

>>> mytextfile=open('C:\\Users\\FEROZ\\first_file.txt')

Make sure to use "\\" if you are accessing the files on windows OS and use "/" if files are on linux system.


Reading a File:

>>> mytextfile=open('first_file.txt')
>>> mytextfile.read()
'This is my first text file to run the python commands.\nI will execute this file to test the result.\nIt is the end of the text file.\n'

--- read it again, what will happen? it won't print the lines.

>>> mytextfile.read()
''                                         ------------------ It only printed '' 

Because, it reads the cursor from the first line to the end of the lines, so now nothing to read anything. If want to read the file more times we need to reset the cursor the cursor back to 0 using seek().

Here is the example:

>>> mytextfile=open('first_file.txt')
>>> mytextfile.read()
'This is my first text file to run the python commands.\nI will execute this file to test the result.\nIt is the end of the text file.\n'
>>> mytextfile.read()
''                               ------------------------ It returns nothing    
>>> mytextfile.seek(0)
0                                ----------------------- reset the cursor back to 0
>>> mytextfile.read()   ------------------- read the file again and we see it printed the text 
'This is my first text file to run the python commands.\nI will execute this file to test the result.\nIt is the end of the text file.\n'
>>>

Note: You could see all the lines are resulted in a single line text with '/n'  without making new lines. You can read a file line by line using readlines().

Here is the example to read the file line by line and result in a List.

>>> mytextfile.readlines()
['This is my first text file to run the python commands.\n', 'I will execute this file to test the result.\n', 'It is the end of the text file.\n']

Important to remember, whenever you open a file and finished your work, it is always recommended and a good practice to close the files.

>>> mytextfile.close()


Writing to a File

Use "w" arguments to write to a File. By default, open() function will only allow reading a file.

Steps:
1. open a file
2. read a file
3. open a file in a write mode
4. write a text in a file
5. reset the cursor to 0
6. read a file


>>> mytextfile=open('first_file.txt')
>>> mytextfile.read()
'This is my first text file to run the python commands.\nI will execute this file to test the result.\nIt is the end of the text file.\n'
>>> mytextfile=open('first_file.txt','w+')
>>> mytextfile.write('This is a new text file!')
24
>>> mytextfile.seek(0)
0
>>> mytextfile.read()
'This is a new text file!'     -------------- next text in the existing file

Note: It's important to remember if you try to open a existing file with "w" or "w+" write mode then all the contents of the file get truncated and it will make an empty file. Generally, "w" or "w+"  commands will try to create a new text file if it doesn't exist, and if exists already it will over write the existing file. So be careful before using these arguments.

Appending to a File

Use argument "a" to open a file and append the lines at the end of the file. If the file doesn't exists it will create a new file, but if the file exists it will append to a file.

>>> mysecondfile=open('second_text_file.txt','a+')
>>> mysecondfile.write('\nIf the file exists if appends to the last line else it would be a first line of the file')
89
>>> mysecondfile.write('\nIf the file was not exists then this would be the second line of the file')
74
>>> mysecondfile.seek(0)
0
>>> mysecondfile.read()
'\nIf the file exists if appends to the last line else it would be a first line of the file\nIf the file was not exists then this would be the second line of the file'

>>> print(mysecondfile.read())
If the file exists if appends to the last line else it would be a first line of the file
If the file was not exists then this would be the second line of the file

>>> mysecondfile.close()


>>> for my_result in open('second_text_file.txt'): print(my_result);
...

If the file exists if appends to the last line else it would be a first line of the file

If the file was not exists then this would be the second line of the file



Comments

Popular posts from this blog

Auditing in Oracle database

rs.stepDown() in MongoDB replication

Tuples in Python