woneuy01 / python2

0 stars 0 forks source link

list #1

Open woneuy01 opened 4 years ago

woneuy01 commented 4 years ago

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.

woneuy01 commented 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

some code that references the variable lin

some other code not relying on fileref # step 4

woneuy01 commented 4 years ago

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])

read()값이 통으로 나온다.

infile.close()

woneuy01 commented 4 years ago

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")

output the header row

outfile.write('Name,Age,Sport') outfile.write('\n')

output each of the rows:

for olympian in olympians: row_string = '{},{},{}'.format(olympian[0], olympian[1], olympian[2]) outfile.write(row_string) outfile.write('\n') outfile.close()

woneuy01 commented 4 years ago

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]))

woneuy01 commented 4 years ago

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"),

"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")

output the header row

outfile.write('"Name","Age","Sport"') outfile.write('\n')

output each of the rows:

for olympian in olympians: row_string = '"{}", "{}", "{}"'.format(olympian[0], olympian[1], olympian[2]) outfile.write(row_string) outfile.write('\n') outfile.close()