11.6 Writing Text Files¶
Note in Table 1 in 11.1 that the only difference between opening a file for writing and opening a file for reading is the use of the w
flag instead of the r
flag as the second parameter.
- open(filename,'r')
for open and read a file
- open(filename,'w')
for open and write a file
- filevariable.close()
close a file
- Table 2 in 11.5 shows the
write
function to add data to text file. - Notice that the
write
method takes one parameter, a string.- When used, the characters of the string will be added to the end of the file.
- YOUR job to add a newline if desired
- When writing, you need to include a newline
\n
- When writing, you need to include a newline
-
Example in the title, then a good while loop example
infile = open("ccdata.txt", "r") aline = infile.readline() print("Year\tEmmision\n") while aline: items = aline.split() dataline = items[0] + '\t' + items[2] print(dataline) aline = infile.readline() infile.close()
Year Emmision
1850 2.24E-7 1860 3.94E-7 1870 6.6E-7 1880 1.1 1890 1.72 1900 2.38 1910 3.34 1920 4.01 1930 4.53 1940 5.5 1950 6.63 1960 10.5 1970 16 1980 20.3 1990 22.6 2000 24.9 2010 32.7 2019 33.3
Creating an output file¶
- To start, we need to open a new output file by adding another call to the
open
function,outfile = open("emissiondata.txt",'w')
, using thew
flag. - We can choose any file name we like. If the file does not exist, it will be created. However, if the file does exist, it will be overwritten
- Once the file has been created, we just need to call the
write
method passing the string that we wish to add to the file. -
In the previous case, the string is already being printed so we will just change the
print
into awrite
method.- A newline needs to be added as well
infile = open("ccdata.txt", "r") outfile = open("emissiondata.txt", "w") aline = infile.readline() outfile.write("Year \tEmmision\n") while aline: items = aline.split() dataline = items[0] + '\t' + items[2] outfile.write(dataline + '\n') aline = infile.readline() infile.close() outfile.close()
Output in emmissiondata.txt: Year Emmision 1850 2.24E-7 1860 3.94E-7 1870 6.6E-7 1880 1.1 1890 1.72 1900 2.38 1910 3.34 1920 4.01 1930 4.53 1940 5.5 1950 6.63 1960 10.5 1970 16 1980 20.3 1990 22.6 2000 24.9 2010 32.7 2019 33.3
- A newline needs to be added as well