Python Open File and Read Contents Solve Math

Python Bites: Manipulating Text Files

Read, write, and append

Photo past Patrick Fore on Unsplash

Text files are commonly used to store data. Thus, they are essential in the information science arrangement. Python provides versatile functions and methods to handle text file.

There are many options to create a text file. Nosotros will not cover all of them since the focus here is to dispense text files, not creating them. Let's go with a method that yous tin can use in a jupyter notebook.

          %%writefile myfile.txt
Python is awesome
This is the second line
This is the last line

We at present have a text file named "myfile.txt" in the current working directory. In guild to read the content of a text file, we first need to open it.

          f = open("myfile.txt")        

We can at present read the content of "myfile.txt".

          f.read()
'Python is awesome\nThis is the second line\nThis is the final line'

The read office, as its name suggests, reads the content of the file. Yous may have noticed that the new lines are indicated with "\north".

It is possible to read the content of the file line by line using the readlines function. It returns a list that contains each line as an item.

          f.readlines()
[]

Our readlines function returns an empty list which is a flake of a problem. The reason is that once you read a file, the cursor goes until the end. The next time y'all try to read the aforementioned file, the cursor cannot find anything to read considering information technology is already at the finish of the file.

The solution is to gear up the cursor back to the initial position. Then, we volition exist able read the file once again.

          f.seek(0)
0
f.readlines()
['Python is awesome\n', 'This is the 2nd line\due north', 'This is the last line']

We should close a file once the content is read. Otherwise, we may run into unexpected results.

          f.close()        

If you effort to read a file afterward information technology's closed, Python raises a value error indicating an I/O functioning on a closed file.

We can also write to an existing file. The style parameter is used for selecting the blazon of operation. The default value is 'r' which stands for read. Thus, we practice not demand to specify the value of way parameter when reading a file.

If yous want to overwrite the content, the mode is gear up as 'west'. It is also possible to add together new content to an existing file which is done by the append option ('a').

We will also get over examples that demonstrate how to overwrite a file or suspend new content. Before going into that part, I'd like to introduce a new method of opening files.

Information technology may sound like a ho-hum performance to close the file each time you read information technology. Luckily, Python provides a more applied way of reading and writing files.

          with open("myfile.txt", style='r') equally f:
content = f.read()
print(content)
Python is awesome
This is the 2d line
This is the last line

We do not need to explicitly phone call the close method on the file anymore. Permit'southward add a new file to our file. We should select the append choice.

          with open("myfile.txt", style='a') every bit f:
f.write("\nTHIS IS THE NEW LINE")

Here is the new content.

          with open("myfile.txt", fashion='r') equally f:
updated_content = f.read()
print(updated_content)
Python is awesome
This is the 2nd line
This is the concluding line
THIS IS THE NEW LINE

The write way overwrites a file. Thus, information technology deletes what is already in the file and writes the new content.

          with open("myfile.txt", style='w') equally f:
f.write("THIS Will OVERWRİTE THE EXISTING LINES")

Let'southward read the new content.

          with open up("myfile.txt", mode='r') equally f:
updated_content = f.read()
print(updated_content)
THIS Will OVERWRİTE THE EXISTING LINES

The mode parameter besides accepts arguments that allow multiple operations. For example, "r+" opens a file for both reading and writing.

          with open up("myfile.txt", way='r+') as f:
content = f.read()
f.write("\nHere is a new line")
f.seek(0)
updated_content = f.read()

Nosotros open the file and read its content. And so we write a new line and read the updated content.

          print(content)
THIS Will OVERWRİTE THE EXISTING LINES
print(updated_content)
THIS WILL OVERWRİTE THE EXISTING LINES
Here is a new line

Conclusion

We have done a few simple examples to show how Python handles reading and writing text files. There is, of class, more to it. This commodity tin can be considered as an introduction that will become you familiar with the operations.

It is always of import to have a comprehensive agreement of the nuts. Y'all will gain advanced skills by building upwardly your knowledge of the basics.

Cheers for reading. Please let me know if y'all have any feedback.

pattonened1998.blogspot.com

Source: https://towardsdatascience.com/python-bites-manipulating-text-files-511d1257d399

0 Response to "Python Open File and Read Contents Solve Math"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel