#fileIO.py #(re)create a text file, put some random numbers in it, one per line, close it. #then open it, or similar file, for reading; read it all import random fname = input("Name of the file to create: ") outf = open(fname, mode="w") #mode: w_rite, a_ppend, r_ead num = int(input("How many random integers to put into the file: ")) for i in range(num): outf.write(str(random.randint(1,100))+"\n") #one number per line outf.close() #not req'd but good practice. Esp. for output files, to flush buffer? #Look at the file in your folder print() fname = input("Name of existing file to read numbers from: ") inf = open(fname, "r") #optional r mode print(inf.readable()) #boolean that indicates whether file is readable nums = inf.readlines() #list of strings, e.g. '23\n' #print("type(nums):", type(nums)) #print(nums) inf.close() nums = [int(i) for i in nums] #convert to list of ints. File must be one number per line print(nums) #inf.read() #entire file as a string, including the \n's #inf.read(n) #n chars #inf.readlines() #entire file as a list of strings, each with \n #inf.readline() #next line as a string, incl. its \n with open(fname) as inf: all_stuff = inf.read() #then closes it #print(all_stuff) with open(fname+"2", "w") as outf: print("hello test", file=outf) #Bonus: open any file for reading, read line by line print() fname = input("Name of text file to read its lines: ") inf = open(fname, "r") num_lines = num_chars = num_words = 0 for line in inf: # includes the \n num_lines += 1 num_chars += len(line) #newline not included num_words += len(line.split()) print("#Lines:", num_lines, "#chars:", num_chars, "#words:", num_words) inf.close() # OR lines = [ line for line in open(fname) ] #read in all lines into a list num_lines = len(lines) num_chars = num_words = 0 for line in lines: num_chars += len(line) num_words += len(line.split()) print("#Lines:", num_lines, "#chars:", num_chars, "#words:", num_words) inf.close() #file format: #fips,name,state,population,percapIncome,medianHouseholdIncome,area #5137,Stone,AR,12663,17190,31364,606.41 print() counties = [line.rstrip().split(',')[1:4] for line in open("datafile_countiesCSV.txt")\ if not line.startswith("fips")] #skip header first line print(counties) print() counties = [[name,state,int(population)] for (name,state,population) in counties\ if int(population)<50000] print(counties) #can this be all in one comprehension?