T
T
Timebird2016-02-28 22:46:24
Python
Timebird, 2016-02-28 22:46:24

How to operate with lines received from a file?

There is a file where some numbers are written on each line. We need to read these numbers and, let's say, multiply each of them by 2. Can you give an example code? Why is mine not working?

a = open('sometext.txt', 'r')
b = []
b = a.readlines()
for line in a.readlines():
  line = int(line) * 2
  b.append(line)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimonchik, 2016-02-28
@Timebird

Padawans get used to clearing strings from dark characters like '\n'
or
or
By the way, as a debugger, a simple print or pprint.pprint() helps a lot
here too

b = a.readlines()
for line in a.readlines():

extra something, for example list b

E
Evgeniy _, 2016-02-29
@GeneD88

ejiffjwei 2
qehfiuefw 4

with open("sometext.txt") as f:
    data = f.readlines()
    print [int(filter(str.isdigit, st))*2 for st in data]

output: [4,8]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question