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.
Forum Archive
How to read files?
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.
Untuk membuka file dat, pertama klik dua kali pada file dan lihat apakah komputer dapat membuka file atau tidak.
Jika komputer Anda dapat membuka dan menampilkan konten dengan jelas, tidak akan terjadi masalah.
Jika Anda tidak tahu cara membuka dan membaca file dat, komputer Anda akan menampilkan kotak dialog Open with dan meminta Anda untuk memilih program yang akan dibuka.
1. Periksa ukuran file dengan mengklik kanan file, pilih Properties. Jika file tersebut besar, itu bisa berupa file video. Karena itu Anda dapat memilih pemutar video seperti Windows Media Player atau VLC Player untuk membuka file.
2.Jika file berukuran sekitar 5 - 15 MB, itu mungkin file audio. Anda juga dapat menggunakan pemutar musik seperti Windows Media Player atau VLC Player untuk membuka file.
3.Jika file dat pada VCD Anda dapat membuka file pada pemutar video.
4) Jika file dat muncul di email Anda, Anda harus sangat berhati-hati karena mereka dapat melampirkan malware. Jika email tersebut dari pengguna tepercaya, seseorang yang Anda kenal, Anda harus membukanya sebaliknya.