This is a simple example of one way you can read and write information from files with Python.
1. To run this code, just copy and paste it into a file in your text editor of choice, then save it with the extension “.py”
2. Then open a terminal and navigate the the folder where you saved the file using cd
, ls
, and cd ..
3. Once in the correct directory type: python3 yourfilename.py
then hit enter.
4. You should see numbers in the terminal, and a new file in the directory.
#this is a simple program that demonstrates how to open a file in python and write to it,
#and then open the same file and read from it, printing the contents to the terminal
#first open the file
#if a file named "sample.txt" already exists in your current directory
#this will overwrite it.
fw = open('sample.txt', 'w+')
#write a simple string to the top of the file
fw.write("hey this is a new file")
#loop through 1000, printing each number and its squared value
for x in range(1, 1000):
message = "the number " + str(x) + " squared is " + str(x**2) + "\n"
#output the string to the file
fw.write(message)
#close the file
#this is very important to do.
#if you don't the file will stay open taking up cpu processing power
#and preventing other applications from accessing if
fw.close()
#re-open the file to read the contents
fr = open('sample.txt', 'r')
#store the contents of the file in a variable
text = fr.read()
#print the contents
print(text)
#close file
fr.close()