How to read integers from file to list? - python

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

Related

How do I fix this ValueError?

I am trying to get an average from a text file that uses a def function. I am trying to convert the list from the text file to int(). Instead of converting it gives me the error: " ValueError: invalid literal for int() with base 10: '5, 5, 6, 7' ". The "5, 5, 6, 7" is one that I made from the proper .txt file. Here is the code:
def getNumberList(filename):
with open(filename,'r') as f:
lyst = f.read().split('\n')
numberList = [int(num) for num in lyst]
return numberList
def getAverage(filename, func):
numbers = func(filename)
return sum(numbers)/len(numbers)
def main():
filename = input("Input the file name: ")
average = getAverage(filename, getNumberList)
print(average)
if __name__ == "__main__":
main()
You are splitting by line but you are not splitting by commas, so you are trying to convert 5,5,6,7 to an integer, which is impossible. You need to also split by commas after you split by line, and then combine them into one list, if you want to average all the numbers in the file. The following should work:
def getNumberList(filename):
with open(filename,'r') as f:
lines = f.readlines()
numberList = [int(num) for num in line.split(',') for line in lines]
return numberList
Looks like you might need to split each element with lyst using "," because right now it is trying to convert each line which has "1,2,3" as input.
So, change this and try.
def getNumberList(filename):
with open(filename,'r') as f:
lyst = []
temp = f.read().strip().split('\n')
for i in temp:
lyst += i.strip().split(',')
numberList = [int(num) for num in lyst]
return numberList

setting the first line read from a file if it is an int, as the end limit of a for loop in python

Currently learning python, what I need to do is set the limit of a for loop equal to the int version of the first item read in a file
for example:
if a file contains the list:
10
1
2
3
4
...
I want the first line which contains 10, as the end limit for a for loop.
or maybe there is another way to accomplish this, that would also be appreciated.
here is what i have code:
otherFile = input("Do you have a file to open? (Y/N): ")
while(otherFile == 'Y' or otherFile == 'y'):
totalSum = 0
try:
with open(input("which file would you like to open? "), "r") as file:
for line in file:
totalSum += int(line)
print(line, end="")
print()
print("Total Sum is: ", totalSum)
except FileNotFoundError:
print("File name invalid, Please enter valid name.")
print()
except ValueError:
print("Invalid data type within file.")
otherFile = input("Do you have another file to open? (Y/N): ")
print("Goodbye")
I tried to read only the first line and turning that into an int, then setting it to limit but it did not work, i show that below:
with open(input("which file would you like to open? "), "r") as file:
numLines = int(file.readline())
for line in numLines: <---------- #what I tried
totalSum += int(line)
print(line, end="")
print()
print("Total Sum is: ", totalSum)
Do not cast string into int if you need a list you may create an integer list like this
integers="10 20 30 40"
integers = list(map(int,integers.split(" ")))
Following code can be useful for setting the limit for range
x=fh.readline()
limit_to_set=int(x.split(" ")[0])
for i in range(0,limit_to_set):
# perform your operation
# just showing what is in this file
>>> with open('file_1', 'r') as f:
... for line in f:
... print(line.rstrip())
...
2
abc
def
ghi
jkl
# print only 2 lines
>>> with open('file_1', 'r') as f:
... for _ in range(int(next(f))):
... print(next(f).rstrip())
...
abc
def
If you do it this way and there is a file where the number in the first line is greater than the total number of lines, you will have to handle the StopIteration on your own.
One way would be to write a code like this:
import pandas as pd
df = pd.read_csv('test.txt', delimiter = ' ')
num = df.columns[0]
num here is the integer you are seeking, than you can run your loop like this:
for i in range(num):
when dealing with integers you should use range()

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

Recreating a sentence using text files and lists

I am relatively new to Python and I am currently working on a compression program that uses lists containing positions of words in a lists and a list of words that make up the sentence. So far I have written my program inside two functions, the first function; 'compression', gets the words that make up the sentence and the positions of those words. My second function is called 'recreate', this function uses he lists to recreate the sentence. The recreated senetence is then stored in a file called recreate.txt. My issue is that the positions of words and the words that make up the sentence are not being written to their respective files and the 'recreate' file is not being created and written to. Any help would be greatly appreciated. Thanks :)
sentence = input("Input the sentence that you wish to be compressed")
sentence.lower()
sentencelist = sentence.split()
d = {}
plist = []
wds = []
def compress():
for i in sentencelist:
if i not in wds:
wds.append(i)
for i ,j in enumerate(sentencelist):
if j in (d):
plist.append(d[j])
else:
plist.append(i)
print (plist)
tsk3pos = open ("tsk3pos.txt", "wt")
for item in plist:
tsk3pos.write("%s\n" % item)
tsk3pos.close()
tsk3wds = open ("tsk3wds.txt", "wt")
for item in wds:
tsk3wds.write("%s\n" % item)
tsk3wds.close()
print (wds)
def recreate(compress):
compress()
num = list()
wds = list()
with open("tsk3wds.txt", "r") as txt:
for line in txt:
words += line.split()
with open("tsk3pos.txt", "r") as txt:
for line in txt:
num += [int(i) for i in line.split()]
recreate = ' '.join(words[pos] for pos in num)
with open("recreate.txt", "wt") as txt:
txt.write(recreate)
UPDATED
I have fixed all other problems except the recreate function which will not make the 'recreate' file and will not recreate the sentence with the words, although
it recreates the sentence with the positions.
def recreate(compress): #function that will be used to recreate the compressed sentence.
compress()
num = list()
wds = list()
with open("words.txt", "r") as txt: #with statement opening the word text file
for line in txt: #iterating over each line in the text file.
words += line.split() #turning the textfile into a list and appending it to num
with open("tsk3pos.txt", "r") as txt:
for line in txt:
num += [int(i) for i in line.split()]
recreate = ' '.join(wds[pos] for pos in num)
with open("recreate.txt", "wt") as txt:
txt.write(recreate)
main()
def main():
print("Do you want to compress an input or recreate a compressed input?")
user = input("Type 'a' if you want to compress an input. Type 'b' if you wan to recreate an input").lower()
if user not in ("a","b"):
print ("That's not an option. Please try again")
elif user == "a":
compress()
elif user == "b":
recreate(compress)
main()
main()
A simpler ( yet less efficient ) approach :
recreate_file_object = open ( "C:/FullPathToWriteFolder/recreate.txt" , "w" )
recreate_file_object.write ( recreate )
recreate_file_object.close ( )

Python write random integers to file on newline

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

Categories

Resources