Job Oriented Experience based CIU Certifications Accredited by QAHE 'USA

   






Python Basics with Files in Python

Python Basics with Files in Python

In Python, files are used to store data permanently so that we can access and modify it as required. Python provides built-in functions to work with files. Here are some basics of working with files in Python:

Opening a File

To open a file, we use the open() function, which returns a file object. The syntax is as follows:

file_object = open(filename, mode)
Here, filename is the name of the file we want to open and mode is the mode in which we want to open the file.

There are several modes in which we can open a file. The most commonly used modes are:

'r': Read mode. This is the default mode. It opens the file for reading.
'w': Write mode. It opens the file for writing. If the file already exists, it truncates the file to zero length. If the file does not exist, it creates a new file.
'a': Append mode. It opens the file for writing. If the file already exists, it appends the new data to the end of the file. If the file does not exist, it creates a new file.
'x': Exclusive creation mode. It opens the file for writing, but only if the file does not already exist. If the file exists, it raises a FileExistsError.


Closing a File

After we are done with the file, we should close it using the close() method. This releases any system resources used by the file. The syntax is as follows:

file_object.close()
Reading a File
We can read the contents of a file using the read() method. The syntax is as follows:

file_contents = file_object.read()
This reads the entire contents of the file into a string.

Alternatively, we can read the file line by line using a loop. The syntax is as follows:

for line in file_object:
# Do something with the line

Writing to a File

We can write to a file using the write() method. The syntax is as follows:

file_object.write(data)
Here, data is the data we want to write to the file.

Example
Here's an example that demonstrates the above concepts:

# Open a file in write mode
file_object = open("example.txt", "w")

# Write some data to the file
file_object.write("Hello, world!\n")

# Close the file
file_object.close()

# Open the file in read mode
file_object = open("example.txt", "r")

# Read the contents of the file
file_contents = file_object.read()

# Print the contents of the file
print(file_contents)

# Close the file file_object.close()

This code creates a new file called example.txt, writes the string "Hello, world!\n" to the file, and then reads the contents of the file and prints it to the console.

Python Basics with Files in Python

Job Oriented CIU Certifications