Data comes in many "types". There are file types that have extensions .csv or .txt or .xls. The .csv means comma separated, the text means text file, and .xls is an Excel file type. There are many others. But, we are only concerned with these three: .csv, .txt, or .xls.
Let's assume you have Python installed (you can install Python in many ways. The easiest is to use Anaconda for Windows or Mac. It's free.
Text files can contain actual text data or table data. We are going to load only table data.
Reading a Text File Step 1: Assign the file name as a variable to a string. >>filename = 'mydata.txt'
Step 2: Pass the file name to the function "open" and also pass it the argument "mode = r" which makes sure that we can only read it. >>file = open(filename, mode='r') # 'r' is to read
Step 3: Assign the text from the file to a variable text by applying the method to the connection to the file. >>text=file.read()
Step 4: Close the connection to the file. >>file.close()
Printing the File to the Console print(text)
BEST Practice - Context Manager With. Now that you see the basic steps, let's add "context" so that we can open the file and print it using one command that will automatically close the file.
>>with open('filename.txt', 'r') as file: print (file.read()) Here you are "binding" a variable in the context manager construct while still within this construct, the variable file will be bound to open file name 'r"
Side Note: To write to a file: >>file = open(filename, mode='w') # 'w' is to write 0 Comments