How to read files?
LordHph last edited by
I am new to python. I am taking the coursera course on python in which they have given a .txt file. I have to find all the numerical values in that text file and compute their sum. How can I do this in Pythonista? I have the code ready. I want to run my code on my file.
ccc last edited by
Please paste your code here like this so we have something to start with.
Your code here...
JonB last edited by
First, you need to share the txt file to pythonista, or use iCloud, etc to copy it into the same folder where your python script lives.
Then, you can use normal methods for reading files on python ... read, readline, for line in file, various methods for reading csv, or other formatted files, ...
with open('your_filename') as f: data=read(f)
bennr01 last edited by ccc
Shouldn't it be
I have to find all the numerical values in that text file and compute their sum. How can I do this in Pythonista?
Assuming each line has exactly one numerical value:
def read_ints_from_file(filepath): """ Read integers from file path filepath. """ values =  # open file read-only with open(filepath, "r") as fin: # read file line by line for line in fin: # remove any leading/trailing whitespace characters and convert to integer v = int(line.strip()) values.append(v) return values # example usage. sum() calculates the sum of the argument(s) print(sum(read_ints_from_file("path/to/textfile.txt")))
If the file contains text other than the numbers, you should look into regular expressions (using
re) to find the values.
GamesBx2020 last edited by
This post is deleted!