Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
How to read files?
-
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.
-
Please paste your code here like this so we have something to start with.
```python
Your code here...
``` -
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)
-
@JonB said:
data=read(f)
Shouldn't it be
f.read()
?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. -
This post is deleted!