Syntax and Usage
Now that you're familiar with file input and output, read this for more on syntax and usage.
Files: Writing to Files
Let's first see how to write to a file:
Example: Let's ask the user to enter a positive integer n and a file name, create a file with the given file name and put the squares of the first n positive integers into it, separated by space.
Type in the following in the Python Shell:
>>> myOut = open("out.txt", 'w')
>>> myOut.write("Hello, my name is Fran.\n")
>>> myOut.write("I like to dance ")
>>> myOut.write("and sing.")
>>> myOut.close()
Let's try to find the file we just created:
Open the folder containing all the programs you worked on today.
Or, do the following:
>>> myOut = open("out.txt") >>> print(myOut.read()) >>> myOut.close()
We can add more to the file that already exists:
Type in the following in the Python Shell:
>>> myOut = open("out.txt",'a') >>> myOut.write("I went to the circus today.") >>> myOut.close()
Then find the file and see how it changed. Or, do the following:
>>> myOut = open("out.txt") >>> print(myOut.read()) >>> myOut.close()
You can find this program in the file workWithFiles5.py
Methods for writing to a file
Method | Description |
open(<filename>, 'w') open(<filename>, 'a') |
open the file for writing ('w') or appending ('a') |
write(<text> |
writes a string <text> |
Example: Let's ask the user to enter a positive integer n and a file name, create a file with the given file name and put the squares of the first n positive integers into it, separated by space.
n = int(input("Enter a positive integer:")) if n > 0: fname = input("Please enter a file name:") output = open(fname + ".txt",'w') for i in range(1,n+1): output.write(str(i*i)+' ') output.close() print("Done! Look for the file",fname+'.txt') else: print("positive integer is expected!")
You can find this program in the file workWithFiles6.py