Python write random integers to file on newline - python

I need to make a program that generates 10 random integers between 10 and 90 and calls two separate functions to perform separate actions. The first one (playlist) simply needs to print them all on one line without spaces, which was easy. The second one (savelist) is giving me problems. I need to write every number in the list nums to angles.txt with each number on a separate line in order. No matter what I try I can't get them on separate lines and it appears as one string on a single line. What am I missing?
import random
def main():
nums = []
# Creates empty list 'nums'
for n in range(10):
number = random.randint(10, 90)
nums.append(number)
# Adds 10 random integers to list
playlist(nums)
savelist(nums)
def playlist(numb):
index = 0
while index < len(numb):
print(numb[index], end=' ')
index += 1
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
myfile.write(str(number) + '\n')
myfile.close()
main()

In savelist(), you need to loop through the list:
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for e in number:
myfile.write(str(e))
myfile.close()
When you send "nums" to savelist(), you are sending a list. If you just try to write "numbers" to the file, it's going to write the whole list. So, by looping through each element in the list, you can write each line to the file.

To write a list to a file you need to iterate over each element of the list and write it individually, with the attached newline. For example:
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for n in number:
myfile.write(str(number) + '\n')
myfile.close()
You could also generate a single string by joining your list with newlines, and then write that to the file. For example:
myfile.write('\n'.join([str(n) for n in number])
Finally, you may want to consider using a context manager on the file open, to ensure that the file is closed whatever happens. For example:
def savelist(nums):
# Creates numbers.txt file
nums.sort()
with open('angles.txt', 'w') as myfile:
myfile.write('\n'.join([str(n) for n in nums])
Note that I also changed the variable name to nums rather than number ('number' is slightly confusing, since the list contains >1 number!).

Try this code out: You are writing an array as a whole to the file, and therefore are seeing only one line.
def main():
nums = [] # Creates empty list 'nums'
for n in range(10):
number = random.randint(10, 90)
nums.append(number)
# Adds 10 random integers to list
playlist(nums)
savelist(nums)
def playlist(numb):
index = 0
while index < len(numb):
print(numb[index], end=' ')
index += 1
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for element in number:
myfile.write(str(element) + '\n')
myfile.close()
main()

#tomlester already stated that you need to loop through the elements in number. Another way to do this is.
def savelist(number):
number.sort()
with open('angles.txt', 'w') as myfile:
myfile.write('\n'.join(map(str, number)))

Here's how I would do it:
from random import randint
def rand_lst(lo, hi, how_many):
return [randint(lo, hi) for _ in range(how_many)]
def print_lst(nums):
print(''.join(str(num) for num in nums))
def save_lst(nums, fname):
with open(fname, "w") as outf:
outf.write('\n'.join(str(num) for num in sorted(nums)))
def main():
nums = rand_lst(10, 90, 10)
print_lst(nums)
save_lst(nums, "angles.txt")
if __name__ == "__main__":
main()

Related

How to read an input file of integers separated by a space using readlines in Python 3?

I need to read an input file (input.txt) which contains one line of integers (13 34 14 53 56 76) and then compute the sum of the squares of each number.
This is my code:
# define main program function
def main():
print("\nThis is the last function: sum_of_squares")
print("Please include the path if the input file is not in the root directory")
fname = input("Please enter a filename : ")
sum_of_squares(fname)
def sum_of_squares(fname):
infile = open(fname, 'r')
sum2 = 0
for items in infile.readlines():
items = int(items)
sum2 += items**2
print("The sum of the squares is:", sum2)
infile.close()
# execute main program function
main()
If each number is on its own line, it works fine.
But, I can't figure out how to do it when all the numbers are on one line separated by a space. In that case, I receive the error: ValueError: invalid literal for int() with base 10: '13 34 14 53 56 76'
You can use file.read() to get a string and then use str.split to split by whitespace.
You'll need to convert each number from a string to an int first and then use the built in sum function to calculate the sum.
As an aside, you should use the with statement to open and close your file for you:
def sum_of_squares(fname):
with open(fname, 'r') as myFile: # This closes the file for you when you are done
contents = myFile.read()
sumOfSquares = sum(int(i)**2 for i in contents.split())
print("The sum of the squares is: ", sumOfSquares)
Output:
The sum of the squares is: 13242
You are trying to turn a string with spaces in it, into an integer.
What you want to do is use the split method (here, it would be items.split(' '), that will return a list of strings, containing numbers, without any space this time. You will then iterate through this list, convert each element to an int as you are already trying to do.
I believe you will find what to do next. :)
Here is a short code example, with more pythonic methods to achieve what you are trying to do.
# The `with` statement is the proper way to open a file.
# It opens the file, and closes it accordingly when you leave it.
with open('foo.txt', 'r') as file:
# You can directly iterate your lines through the file.
for line in file:
# You want a new sum number for each line.
sum_2 = 0
# Creating your list of numbers from your string.
lineNumbers = line.split(' ')
for number in lineNumbers:
# Casting EACH number that is still a string to an integer...
sum_2 += int(number) ** 2
print 'For this line, the sum of the squares is {}.'.format(sum_2)
You could try splitting your items on space using the split() function.
From the doc: For example, ' 1 2 3 '.split() returns ['1', '2', '3'].
def sum_of_squares(fname):
infile = open(fname, 'r')
sum2 = 0
for items in infile.readlines():
sum2 = sum(int(i)**2 for i in items.split())
print("The sum of the squares is:", sum2)
infile.close()
Just keep it really simple, no need for anything complicated. Here is a commented step by step solution:
def sum_of_squares(filename):
# create a summing variable
sum_squares = 0
# open file
with open(filename) as file:
# loop over each line in file
for line in file.readlines():
# create a list of strings splitted by whitespace
numbers = line.split()
# loop over potential numbers
for number in numbers:
# check if string is a number
if number.isdigit():
# add square to accumulated sum
sum_squares += int(number) ** 2
# when we reach here, we're done, and exit the function
return sum_squares
print("The sum of the squares is:", sum_of_squares("numbers.txt"))
Which outputs:
The sum of the squares is: 13242

I want to write a function which prints a sum

I just started learning Python a few weeks ago and I want to write a function which opens a file, counts and adds up the characters in each line and prints that those equal the total number of characters in the file.
For example, given a file test1.txt:
lineLengths('test1.txt')
The output should be:
15+20+23+24+0=82 (+0 optional)
This is what I have so far:
def lineLengths(filename):
f=open(filename)
lines=f.readlines()
f.close()
answer=[]
for aline in lines:
count=len(aline)
It does what I want it to do, but I don't know how to include all the of numbers added together when I have the function print.
If you only want to print the sum of the length of each line, you can do it like so:
def lineLengths(filename):
with open(filename) as f:
answer = []
for aline in f:
answer.append(len(aline))
print("%s = %s" %("+".join(str(c) for c in answer), sum(answer))
If you however also need to track lengths of all the individual lines, you can append the length for each line in your answer list by using the append method and then print the sum by using sum(answer)
Try this :
f=open(filename)
mylist = f.read().splitlines()
sum([len(i) for i in mylist])
Simple as this:
sum(map(len, open(filename)))
open(filename) returns an iterator that passes through each line, each of which is run through the len function, and the results are summed.
Once you read lines from file you can count sum using:
sum([len(aline) for aline in lines])
Separate you problem in function : a responsible by return total sum of lines and other to format sum of each line.
def read_file(file):
with open(file) as file:
lines = file.readlines()
return lines
def format_line_sum(lines):
lines_in_str = []
for line in lines:
lines_in_str.append(str(line)
return "+".join(str_lines))
def lines_length(file):
lines = read_file(file)
total_sum = 0
for line in lines:
total_sum += len(line)
return format_lines_sum(lines) + "=" + total_sum
And to use:
print(lines_length('file1.txt'))
Assuming your output is literal, something like this should work.
You can use python sum() function when you figure out how to add numbers to the list
def lineLengths(filename):
with open(filename) as f:
line_lengths = [len(l.rstrip()) for l in f]
summ = '+'.join(map(str, line_lengths)) # can only join strings
return sum(line_lengths), summ
total_chars, summ = lineLengths(filename)
print("{} = {}".format(summ, total_chars))
This should have the output you want : x+y+z=a
def lineLengths(filename):
count=[]
with open(filename) as f: #this is an easier way to open/close a file
for line in f:
count.append(len(line))
print('+'.join(str(x) for x in count) + "=" + str(sum(count))

How to read integers from file to list?

def make_number_list(a_file):
number_list= []
for line_str in a_file:
line_list = line_str.split()
for number in line_list:
if number != " ":
number_list.append(number)
return number_list
opened_file = open(input("Name of input file: "))
a_file_list = make_number_list(opened_file)
print(a_file_list)
print("Length: ", len(a_file_list))
I am trying to read (eventually) 1000 integer values from a file into a list.. then find their max, min and i th value. However, this is not working to read the list (I'm just using a test list which is a file in TextEdit and is a bunch of random numbers separated by a single white space). Any suggestions?
# assumes Python 3.x
def read_nums(fname):
with open(fname) as inf:
return [int(i) for i in inf.read().split()]
def main():
fname = input("Name of input file: ")
nums = read_nums(fname)
print("Read {} numbers".format(len(nums)))
if __name__=="__main__":
main()
I am not sure how the numbers are present in your input file. Nonetheless, there are a few changes you could do to your code:
Move the return statement outside the loop.
A better way of checking if number exists would be:
if number.isdigit():
Which gives you:
def make_number_list(a_file):
number_list= []
for line_str in a_file:
line_list = line_str.split()
for number in line_list:
if number.isdigit():
number_list.append(number)
return number_list

Trying to write a python program that reads numbers from a file and computes the sum of the squares

I am trying to write a program that reads numbers from a file and then calculates the sum of the squares of the numbers. This program is supposed to prompt the user for the name of the file and print the sum of the squares. It offers a hint that says use readlines() but this hasn't helped me much. I have tried for hours to come up with a working code but can't get anything to work!!! I am about ready to pull my hair out!!! Here is my code:
Code for my file:
def main():
filename = input("Enter the name for the file: ")
infile = open(filename, 'w')
numList = input('Enter any numbers(seperated by a space): ')
print(numList, file=infile)
main()
Code for my program:
# function to convert list of strings to real numbers
def toNumbers(nums):
for i in range(len(nums)):
nums[i] = int(nums[i])
# function to square the numbers in a list
def numsquare(nums):
for i in range(len(nums)):
nums[i] = nums[i]**2
# function to add the numbers in the list
def sumList(nums):
total = 0
for i in nums:
total = total + i
return total
# program that pulls numbers from file and computes sum of the square of the numbers
def main():
fname = input("Please enter the name of the file to be opened: ")
nums = open(fname, 'r')
print("The numbers in this list are:")
print(nums)
# Convert strings in list to actual numbers
toNumbers(nums)
# Square the numbers in the list
numsquare(nums)
# Get the sum of the numbers in the list
sumList(nums)
total = sumList(nums)
print()
print("The sum of the numbers from this list is:", total)
main()
If anyone could please tell me what I am doing wrong then it would be greatly appreciated. This is my first ever computer science class and any advice is welcome.
Without knowing the structure of the file, I can at least tell you that part of your problem is that you are using the file handle as your "nums" variable which will not give you your content.
In order to pull the data out of the file you will need to call .read() or .readline() on the file handle.
fname = input("Please enter the name of the file to be opened: ")
file = open(fname, 'r')
lines = file.readlines()
lines now contains a list where each entry is the content of one line of your file
If you have one number per a line, you should be able to cast the contents of each list entry to an int to get a list of numbers.
If you have multiple numbers per a line, you need to use split() on each list entry to extract each individual number.
The 'readLines()' return a list. Then you have use a for to navigate in list.
lines = nums.readlines()
The num that receive the return of open(fname, 'r') is a stream and not a text. Therefore you must use nums.readlines() after. See the function map of python, is very util to help you.
The first thing to debug any code is by printing out at different points to check whether you are getting the desired output.
nums = open(frame,'r'); print(nums) You will notice that printing nums does not print the contents of the file 'frame'. To get the contents of the file, you need to do contents = nums.readlines() or contents = nums.read(). The former will give you a list with each entry (which is a string) being one line of the file. The second will give you the entire text converted to a single string.
A sample example is given below:
my_text_file: say f.txt
12 1 2 3 4 5 6
8
21
32
7
nums = open('f.txt','r')
f = nums.readlines() #f = nums.read()
>>>['12 1 2 3 4 5 6\n', '\n', ' 8\n', '\n', '21 \n', '\n', '32\n', '\n', '7']
#The above line is the output for nums.readlines()
>>>'12 1 2 3 4 5 6\n\n 8\n\n21 \n\n32\n\n7'
#The above line is the output for nums.read()
Now you will have to do the appropriate steps to convert the strings to separate the numbers and convert them to int/float and then carry out the calculations.
Here's a working program with comments. Let me know if there's anything you don't understand.
Read the comments (marked with #) to better understand some of the stuff that I added.
Also, if you're using Python 3.x, keep using input() for input, but if you're using Python 2.x, use raw_input() to get input.
# function to convert list of strings to real numbers
def toNumbers(nums):
for i in range(len(nums)):
nums[i] = int(nums[i])
# function to square the numbers in a list
def numsquare(nums):
for i in range(len(nums)):
nums[i] = nums[i]**2
# function to add the numbers in the list
def sumList(nums):
total = 0
for i in nums:
total = total + i
return total
# program that pulls numbers from file and computes sum of the square of the numbers
def main():
fname = input("Please enter the name of the file to be opened: ")
nums = open(fname, 'r')
strings = ""
#create a string rather than a list with readlines
#so we can remove extra spaces with the .split() method later
for line in nums.readlines():
strings += line
#make sure to close nums
nums.close()
#remove spaces and store this result in the list nums_array
nums_array = strings.split()
print("The numbers in this list are:")
print(nums_array)
# Convert strings in list to actual numbers
toNumbers(nums_array)
# Square the numbers in the list
numsquare(nums_array)
# Get the sum of the numbers in the list
sumList(nums_array)
total = sumList(nums_array)
print
print("The sum of the numbers from this list is: " + str(total))
main()
>>> Please enter the name of the file to be opened: i.txt
The numbers in this list are:
['1', '2', '3', '4', '5', '6', '7', '8']
The sum of the numbers from this list is: 204
where i.txt contains:
1 2 3 4
5 6 7 8

Python: How to use a for-loop or while-loop to alphabetize a list in a file

I am both new to programming and python. I need to read a list in a file, use a while-loop or for-loop to alphabetize that list and then write the alphabetized list to a second file. The file is not sorting and it is not writing to the file. Any insight or constructive criticism is welcome.
unsorted_list = open("unsorted_list.txt", "r") #open file congaing list
sorted_list = open ("sorted_list.txt", "w") #open file writing to
usfl = [unsorted_fruits.read()] #create variable to work with list
def insertion_sort(list): #this function has sorted other list
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i = i - 1
else:
break
insertion_sort(usfl) #calling the function to sort
print usfl #print list to show its sorted
sfl = usfl
sorted_furits.write(list(sfl)) #write the sorted list to the file
unsorted_fruits.close()
sorted_fruits.close()
exit()
If insertion_sort worked before, I guess it works now, too. The problem is that usfl contains only one element, the content of the file.
If you have a fruit on each line, you can use this to populate your list:
usfl = [line.rstrip () for line in unsorted_fruits]
or if it is a comma separated list, you can use:
usfl = unsorted_fruits.read ().split (',')
Your problem seems to be the way you're handling files.
Try something along the lines of:
input_file = open("unsorted_list.txt", "r")
output_file = open("sorted_list.txt", "w")
#Sorting function
list_of_lines = list(input_file) #Transform your file into a
#list of strings of lines.
sort(list_of_lines)
long_string = "".join(list_of_lines) #Turn your now sorted list
#(e.g. ["cat\n", "dog\n", "ferret\n"])
#into one long string
#(e.g. "cat\ndog\nferret\n").
output_file.write(long_string)
input_file.close()
output_file.close()
exit()
Let me begin by saying thank you to all the answers. Using the answer here to guide me in searching and tinkering I have produced code that works as required.
infile = open("unsorted_fruits.txt", "r")
outfile = open("sorted_fruits.txt", "w")
all_lines = infile.readlines()
for line in all_lines:
print line,
def insertion_sort(list):
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i = i - 1
else:
break
insertion_sort(all_lines)
all_sorted = str(all_lines)
print all_sorted
outfile.write(all_sorted)
print "\n"
infile.close()
outfile.close()
exit()

Categories

Resources