I'm creating a function that reads a .txt file that contains the following:
Testing.txt:
a 1 34
b 2 25
c 3 23
j 4 80
I need to create a function that reads this file and prints the average of the last 2 digits of each line in the file.
What I have so far is this:
def Stats():
filename = input("Enter a file name: ")
with open(filename) as f:
data = [int(line) for line in f]
print("The average value is ", sum(data)/len(data))
Stats()
Pros:
this function will produce the average of int values within a function.
cons:
It will not work if the file contains str within it.
Question: How can I get my function to work with a file such as the one listed above called (testing.txt)?
I think this is what you are after:
# filename = input("Enter a file name: ")
filename = "input.txt"
def avg_file(filename):
with open(filename, 'r') as f:
data = [int(line.split()[2]) for line in f]
return sum(data)/len(data)
avg = avg_file(filename)
print("The average value is: ", avg)
# The average value is: 40.5
the key is this line.split()[2]. This splits a line based on spaces, and takes 3th value.
You could ignore non-numbers this way:
data = [int(token) for token in f.read().split() if token.isdigit()]
What about something like:
import csv
def mean(lst): return sum(lst) / len(lst)
with open('input.txt') as f:
reader = csv.reader(f, delimiter=' ')
lines = [line for line in reader]
col3 = [int(line[2]) for line in lines]
print(mean(col3)) # 40.5
This just uses the csv module to parse the file lines into rows containing elements. You could accomplish the same thing with something like:
def mean(lst): return sum(lst) / float(len(lst))
with open('input.txt') as f:
lines = [line.split() for line in f]
col3 = [int(line[2]) for line in lines]
print mean(col3) # 40.5
Something like this:
data = [sum(map(int, line.split(' ')[1:])) / 2 for line in f]
Or something more old-school, in case you have unknown mix of string and int values:
data = []
for line in f:
integers = []
for segment in line.split():
try:
integers.append(int(segment))
except ValueError:
pass
data.append(sum(integers) / len(integers))
Related
I have a file that contains the following content. This is a sample of the file. The fine contains up to 1000 values.
'1022409', '10856967', '11665741'
I need to read the file and create this list ['1022409', '10856967', '11665741']
I'm using the following code:
with open('Pafos.txt', 'r') as f:
parcelIds_list = f.readlines()
print (parcelIds_list[0].split(','))
The value is of parcelIds_list parameter is this list ["'1022409', '10856967', '11665741'"] with only index 0.
Any ideas please?
Follow this code
with open ('Pafos.txt', 'r') as f:
# To split
num = f.readline().split(', ')
# To remove ' and create list
# If u want list of string
num_list = [x.replace('\'', '') for x in num]
Output
['1022409', '10856967', '11665741']
If u want list of int
# If u want list of int
num_list = [int(x.replace('\'', '')) for x in num]
Output
[1022409, 10856967, 11665741]
If u have more than one row in file, you need to add some extra line of code
It is a bit hard to code with the few lines you have given from the text file, but try this :
temp = []
with open('Pafos.txt', 'r') as f:
parcelIds_list = f.readlines()
for j in parcelIDS_list:
temp.extend(j.split(", "))
new_list = [i.strip()[1:-1] for i in temp]
print(new_list)
Let me know if this doesn't work, and what went wrong. I will modify my answer likewise.
I found the solution thanks to this.
with open('Pafos.txt', 'r') as f:
parcelIds_list = f.readlines()
cs_mylist = []
for y in [x.split(',') for x in parcelIds_list]:
for z in y:
cs_mylist.append(z.replace(' ', ''))
Probably there is a cleaner way, but this works:
with open('Pafos.txt', 'r') as f:
parcelIds_list = f.readlines()
line = parcelIds_list[0]
line = line.replace("'", "")
line = line.replace(" ", "")
line = line.split(',')
print(line)
# This program asks for an input and output file, and uses mult. and add.
# to combine files
def main():
print("This program creates a file of numbers from a")
print("file of numbers.")
infileName = input("What file are the numbers in? ")
outfileName = input("What file should the numbers go in? ")
infile = open(infileName, 'r')
outfile = open(outfileName, 'w')
for line in infile:
nums = line.split()
nums = float()
first = nums[0]
second = nums[-1]
newfirst = (first + second)
newsecond = (first * second)
print(newfirst, newsecond, file=outfile)
infile.close()
outfile.close()
print("Numbers have been written to", outfileName)
main()
the input txt file looks like this:
4.5 16.8
15 25
150 220.4
5.8 90
-1 -2
6.8 -2.3
this is what i have so far, I know everything is right other than the part where I split the input file. I just want to know how to convert the numbers in the input file to floats so i can add them and multiply them
You should replace this:
nums = line.split()
nums = float()
first = nums[0]
second = nums[-1]
with this:
nums = line.split()
first = float(nums[0])
second = float(nums[-1])
or this:
nums = [float(x) for x in line.split()]
first = nums[0]
second = nums[-1]
How do I calculate the sum of numbers from a .txt file?
Data in file is formatted as:
7
8
14
18
16
8
23
...
I read the data from the file and assign every line value to 'line' vatiable, but I want to get something like: result = 7+8+14+...
f = open('data.txt', 'r') #LOOP AND READ DATA FROM THE FILE
for line in f:
code
This is most compact code I can think of right now:
(updated to handle the n at the end, thanks, #JonClements!)
with open('file.txt', 'r') as fin:
ans = sum(int(line) for line in fin if line.strip().isnumeric())
For the code structure you have, you can also go for this:
f = open('data.txt', 'r')
ans = 0
for line in f:
try:
ans += int(line.strip())
except ValueError:
pass
Edit:
Since the confusion with the 'n' has been cleared, the first example can be as simple as
with open('file.txt', 'r') as fin:
ans = sum(int(line) for line in fin)
Or even this one-liner:
ans = sum(int(line) for line in open('file.txt', 'r'))
But there are certain risks with file handling, so not strongly recommended.
Keep it simple:
with open('data.txt', 'r') as f:
result = sum(map(int, f))
int is mapped over each line from f, then sum() adds up the resulting integers.
file = open("data.txt", "r")
numbers = []
for line in file:
numbers.append(int(line))
print(sum(numbers))
This basically just creates a list of numbers, where each line is a new entry in the list. Then it shows the sum of the list.
A simple solution is, it will take care of the \n at the end of each line as well, based on steven's and AChamp's suggestion
with open("abc.txt","r")as f:
print(sum(int(x) for x in f))
Here is a solution (consider all of the lines are numbers):
def calculate_number_in_file(file_path):
with open(file_path, 'r') as f:
return sum([int(number.strip()) for number in f.readlines()])
with open ('data.txt', 'r') as f:
data = f.readlines()
sum = 0
for line in data:
sum += int(line.strip())
print(sum)
On smartphone...
with open(filepath) as f:
lines = f.readlines()
numbers = [int(line) for line in lines]
print(sum(numbers))
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))
I would like to take a large file like this in Python 2.7:
123 456 GTHGGGTH
223 567 FGRTHSYS
12933 4656832 GJWSOOOSKKSSJ
.....
and I want to read in the file line by line, disregard the third element, and subtract the second element in each line by the first element. Thus line 1 above would return 333.
I have tried this so far:
def deleteLast(list):
NewL = list.pop()
return NewL
f = open(file_name, 'r')
line = f.readline()
while line:
L = line.split()
L2 = deleteLast(L)
L3 = [int(number) for number in L2]
Length = L3[1]-L3[0]
print Length
f.close()
But, when I try this the compiler says:
ValueError: invalid literal for int() with base 10: 'T'
All help is appreciated.
That is because list.pop() is returning the "popped off" item, it doesn't return the list again.
Instead of this deleteLast function you have written, it would be better just to use a slice like this:
L2 = line.split()[0:2]
You are going to run into another problem later because your while loop isn't advancing at all. Consider using a for loop instead.
You can try something like this :
In [8]: with open("abc") as f: #always use with statement when handling files
...: for line in f:
...: x,y=map(int,line.split()[:2])
...: print y-x
...:
333
344
4643899
try the following:
with open(file_name, 'r') as f:
for line in f.readlines():
rowData = line.split()
left, right = map(int, rowData[:2])
length = right - left
print length
Or:
from operator import sub
with open(file_name, 'r') as f:
for line in f.readlines():
print sub(*map(int, line.split()[:2])[::-1])
f = open(file_name, 'r')
for line in f.readlines():
x, y = line.split(' ')[:2]
print int(y) - int(x)