-3

I would like to transform a file that contains one column of numbers (many numbers) like:

1

2

3
...

i

to a one-dimensional list such as [1, 2, 3, ...i].
Any help will be appreciated.

Thanks

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178

3 Answers3

1

Just read the lines of the file, strip the newlines of the ends, and cast to integers:

with open('text.txt') as text:
    data = [int(i.strip()) for i in text if i != '\n'] 
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
1
with open('text.txt', 'r') as file:
    nums = file.readlines()
nums = [i.rstrip('\n') for i in nums]

The second line is to ensure that the newlines are excluded from the list elements when you print nums.

If your file includes blanks, you need to also add this line to exclude empty strings from the final list:

nums = [int(i) for i in nums if i]

if you need to multiply list elements by a factor, say 0.7, you can rewrite the last line like this:

nums = [int(i) * 0.7 for i in nums if i]
Omid
  • 2,617
  • 4
  • 28
  • 43
  • Thanks for your help. However the numbers appears like ['1', '2', '3'...] instead of [1, 2, 3...]. Also is it possible to multiply them with 0.7 before listing? Many thanks. – user2903229 Mar 27 '15 at 10:26
  • Thanks for that, it really helped. Do you know why when I save it as np.savetxt('freqline.dat', nums) is still shows column format? – user2903229 Mar 29 '15 at 19:36
-1

Ah, I have fixed it by adding float in front. So the code looks like this at the moment:

with open('freq.dat', 'r') as file:
File = file.readlines()
nums = np.array(File)
nums = [i for i in nums if i]
nums = [float(i.rstrip('\n')) for i in nums]

print nums
np.savetxt('freqline.dat', nums)

Any tips how to multiply the numbers with a specific value lets say 0.7. It prints the numbs [1,2,3...] now but in the saved text they are still in column format. Any suggestion how to change that?