Learn Python For Data Science (Course I)July 18, 2020 2020-08-04 10:39
Learn Python For Data Science (Course I)
- Welcome to Course I!
- Installing Python and Getting Started
- Data Types and Operations in Python
- Control Flow Tools in Python
- Errors and Exceptions in Python
- Classes and Objects in Python
- Standard Libraries in Python
- Virtual Environments and Packages in Python
- Working with files in Python
- End of Course
Working with files in Python
Python provides built-in functions for working with files. Let us discuss a few operations that can be used for the same.
The open() function returns a file object and is most commonly used with two arguments: open(filename, mode)
f = open('workfile', 'w')
Similarly, the close() function closes the file object and removes any unwritten information. It is simply used in the following form:
The read() function reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). Size is an optional numeric argument. The write() function writes the contents of a passed in string to the file.
Here is an example program that demonstrates a read/write operation in Python.
# Example of file operations for a sample text file # Writing to a file(.txt) with open("sample.txt", 'w', encoding = 'utf-8') as f: f.write("First line\n") f.write("Second line\n") f.write("Third line\n") # Reading from a the same file with open("sample.txt", 'r') as f: print(f.read()) # Closing the file f.close()
OUTPUT: First line Second line Third line