Posts Python Files
Post
Cancel

Python Files

In python you can handle any type of files , it can be csv ,pdf txt or any

Basic operations:

Open a file

1
>>> myfile=open("test_file.txt")

| Ensure you are in the same directory where your file exists if not provide the full path for your file. Above opens the file in readonly mode by default

Read the file

1
2
>>> myfile.read()
   "This is the content\n"

If you retry above You would get empy as now the cursor position is at end of the file

1
2
>>> myfile.read()
()

Repositioning the cursor

To reposition the cursor

1
>>> myfile.seek(0)

| In above 0 represents the position of cursor in your file

Closing the file

1
>>> myfile.close()

Writing to a file (Below overwrites the file i.e Deletes any existing content of the file)

1
2
3
4
5
6
7
8
9
10
11
>>> myfile=open("test_file.txt",'w+') //opens the file
>>>
>>> myfile.write("This is a new line")
18
>>> len("This is a new line")
18
>>> myfile.seek(0) //moves the cursor to the 0th position
0
>>> myfile.read()
'This is a new line'
>>> myfile.close() //Closes the file

test_file.txt content for below example

1
This is a new line\n

Appending (Below appends new line to the existing content)

1
2
3
4
5
6
7
8
9
10
>>> myfile=open("test_file.txt","a+")
>>> myfile.write("This is second line")
19
>>> len("This is second line")
19
>>> myfile.seek(0) // To reposition cursor
0
>>> myfile.read()
'This is a new lineThis is second line'
>>> myfile.close() // Closes the file

test_file.txt content for below example

1
2
3
This is a new line
This is a second line
This is a third line

Printing lines using for loop

1
2
3
4
5
6
7
8
9
10
11
12
13
>>>for line in open('test_file.txt'):
...     print(line)
...
This is a new line

This is second line

This is 3rd line
.read() - Read the file as string characteristics

>>> myfile = open('test_file.txt')
>>> myfile.read()
'This is a new line\nThis is second line\nThis is 3rd line\n'

Readlines output it as list line by line

1
2
3
4
5
6
7
8
9
>>> myfile.readlines()
['This is a new line\n', 'This is second line\n', 'This is 3rd line\n']
To get specific line
>>> myfile.readlines(1)
['This is a new line\n']
>>> myfile.readlines(2)
['This is second line\n']
>>> myfile.readlines(3)
['This is 3rd line\n']

Hope you find this useful.


Thanks for reading till end.

Followus on insta @techpechu

Join Our Discord

We do run a youtube channel in Indian regional language Tamil called TechPechu. Do subscribe us for moral support. Happy Learning.

Follow us on instagram @techpechu