File Handling

We will learn about file handling in Powershell and Python.

Reading from a file

PowerShell offers a fairly simple approach to read files by using the cmdlet Get-Content <file path>. Just provide the full or relative path to the cmdlet, and the content of the file will be returned on our console.

Press + to interact
main.ps1
file.txt
Get-Content /usercode/file.txt

In Python, we have to use a built-in method, open(), which opens a file and returns a stream of data in the file.

To know more about this Python built-in method, use help(open).

Press + to interact
main.py
file.txt
# escape the backslash in the file path
file_handle = open("/usercode/file.txt")
data = file_handle.read() # reads the complete file
print(data) # prints the data
file_handle.close()

In the above example, we first open the file in read-only mode, which is the default mode of the open() method. Then, we use the read() method to capture the data stream from the file and store it in the data variable. Finally, the print() method prints this data on the Python console. It is important to close the file handle so that another program can access the file. This saves memory and avoids certain program errors.

Reading the file line-by-line

When we capture data from a file using the Get-Content cmdlet, we get the complete content of the file. In some scenarios, though, it is necessary to read files in chunks or line-by-line. Data returned using this cmdlet in PowerShell is in the form of an array, which means the first ...