Open woneuy01 opened 4 years ago
fname = "yourfile.txt" with open(fname, 'r') as fileref: # step 1 ## since with open close the file automatically try to use with open more!! lines = fileref.readlines() # step 2 for lin in lines: # step 3
filename = "squared_numbers.txt" outfile = open(filename, "w")
for number in range(1, 13): square = number * number outfile.write(str(square) + "\n")
outfile.close()
infile = open(filename, "r") print(infile.read()[:10])
infile.close()
olympians = [("John Aalberg", 31, "Cross Country Skiing"), ("Minna Maarit Aalto", 30, "Sailing"), ("Win Valdemar Aaltonen", 54, "Art Competitions"), ("Wakako Abe", 18, "Cycling")]
outfile = open("reduced_olympics.csv", "w")
outfile.write('Name,Age,Sport') outfile.write('\n')
for olympian in olympians: row_string = '{},{},{}'.format(olympian[0], olympian[1], olympian[2]) outfile.write(row_string) outfile.write('\n') outfile.close()
fileconnection = open("olympics.txt", 'r') lines = fileconnection.readlines() header = lines[0] field_names = header.strip().split(',') print(field_names) for row in lines[1:]: vals = row.strip().split(',') if vals[5] != "NA": print("{}: {}; {}".format( vals[0], vals[4], vals[5]))
When there is "," inside the string!!!
But it is doable. Indeed, one reason Python allows strings to be delimited with either single quotes or double quotes is so that one can be used to delimit the string and the other can be a character in the string
olympians = [("John Aalberg", 31, "Cross Country Skiing, 15KM"),
("Minna Maarit Aalto", 30, "Sailing"),
("Win Valdemar Aaltonen", 54, "Art Competitions"),
("Wakako Abe", 18, "Cycling")]
outfile = open("reduced_olympics2.csv", "w")
outfile.write('"Name","Age","Sport"') outfile.write('\n')
for olympian in olympians: row_string = '"{}", "{}", "{}"'.format(olympian[0], olympian[1], olympian[2]) outfile.write(row_string) outfile.write('\n') outfile.close()
When the file is on different directory open('../myData/data2.txt', 'r'). The ../ means to go up one level in the directory structure, to the containing folder (allProjects); myData/ says to descend into the myData subfolder.