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
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
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']
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]
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?