4

I want to know whether there is an equivalent statement in lists to do the following. In MATLAB I would do the following

fid = fopen('inc.txt','w')
init =1;inc = 5; final=51;
a = init:inc:final
l = length(a)
for i = 1:l
   fprintf(fid,'%d\n',a(i));
end
fclose(fid);

In short I have an initial value, a final value and an increment. I need to create an array (I read it is equivalent to lists in python) and print to a file.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Vaidyanathan
  • 379
  • 3
  • 6
  • 16
  • 1
    Your title doesn't seem to match your question. – Russell Borogove Aug 20 '13 at 00:55
  • @Russel Borogove pardon me. I actually wrote a different question yesterday for which i got an answer. When i changed the question, i did not know that the title would still remain even after a day ;) – Vaidyanathan Aug 20 '13 at 01:03
  • 1
    @Vaidyanathan BTW you don't really need the loop in MATLAB. `fprintf(fid,'%d\n', a);` would suffice. – Eitan T Aug 20 '13 at 06:47

6 Answers6

14

In Python, range(start, stop + 1, step) can be used like Matlab's start:step:stop command. Unlike Matlab's functionality, however, range only works when start, step, and stop are all integers. If you want a parallel function that works with floating-point values, try the arange command from numpy:

import numpy as np

with open('numbers.txt', 'w') as handle:
    for n in np.arange(1, 5, 0.1):
        handle.write('{}\n'.format(n))

Keep in mind that, unlike Matlab, range and np.arange both expect their arguments in the order start, stop, then step. Also keep in mind that, unlike the Matlab syntax, range and np.arange both stop as soon as the current value is greater than or equal to the stop value.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html

lmjohns3
  • 7,422
  • 5
  • 36
  • 56
  • this is much more generic. Thank you. What is the difference between `with .. as` and `f.open()\f.close()`. Also like matlab inbuilt tutorials with **examples** for python. In the website it looks a lot more jumbled. – Vaidyanathan Aug 20 '13 at 05:35
  • The `with .. as` construct is basically shorthand for `f.open() .. f.close()`, except that `f.close()` is guaranteed to be called in case of an exception ([examples](http://preshing.com/20110920/the-python-with-statement-by-example)). – lmjohns3 Aug 20 '13 at 11:21
  • Python doesn't really have built-in tutorials, but there is one online at http://docs.python.org/2/tutorial/, and there are are many others written by other folks. Try out a couple to get a feel for things. – lmjohns3 Aug 20 '13 at 11:32
4

You can easily create a function for this. The first three arguments of the function will be the range parameters as integers and the last, fourth argument will be the filename, as a string:

def range_to_file(init, final, inc, fname):
    with open(fname, 'w') as f:
        f.write('\n'.join(str(i) for i in range(init, final, inc)))

Now you have to call it, with your custom values:

range_to_file(1, 51, 5, 'inc.txt')

So your output will be (in the fname file):

1
6
11
16
21
26
31
36
41
46

NOTE: in Python 2.x a range() returns a list, in Python 3.x a range() returns an immutable sequence iterator, and if you want to get a list you have to write list(range())

Peter Varo
  • 11,726
  • 7
  • 55
  • 77
2

test.py contains :

#!/bin/env python                                                                                                                                                                                  

f = open("test.txt","wb")                                                                                                                                                                           
for i in range(1,50,5):                                                                                                                                                                             
    f.write("%d\n"%i)

f.close()

You can execute

python test.py

file test.txt would look like this :

1
6
11
16
21
26
31
36
41
46
iamauser
  • 11,119
  • 5
  • 34
  • 52
  • it is prefered to use the `open` function with the `with/as` statement. It will close the file even if an exception occured during the file manipulation. – Peter Varo Aug 20 '13 at 01:29
  • @PeterVaro Thanks alot. It worked. Just a question. Say i am reading in float values in contrast to int, for example then the code will be `for i in range(1.5,51.5,5)`. But this throws an error saying `range() integer end argument expected, got float.` – Vaidyanathan Aug 20 '13 at 05:22
  • @Vaidyanathan You may have to build one of your own for `range()` with floats. See here, http://stackoverflow.com/questions/477486/python-decimal-range-step-value – iamauser Aug 20 '13 at 13:44
1

I think your looking for something like this:

nums = range(10) #or any list, i.e. [0, 1, 2, 3...]
number_string = ''.join([str(x) for x in nums])

The [str(x) for x in nums] syntax is called a list comprehension. It allows you to build a list on the fly. '\n'.join(list) serves to take a list of strings and concatenate them together. str(x) is a type cast: it converts an integer to a string.

Alternatively, with a simple for loop:

number_string = ''
for num in nums:
    number_string += str(num)

The key is that you cast the value to a string before concatenation.

Madison May
  • 2,723
  • 3
  • 22
  • 32
1

I think that the original poster wanted 51 to show up in the list, as well.

The Python syntax for this is a little awkward, because you need to provide for range (or xrange or arange) an upper-limit argument that is one increment beyond your actual desired upper limit. An easy solution is the following:

init = 1
final = 51
inc = 5
with open('inc.txt','w') as myfile:
    for nn in xrange(init, final+inc, inc):
        myfile.write('%d\n'%nn)
dslack
  • 835
  • 6
  • 17
0
open('inc.txt','w').write("\n".join(str(i) for i in range(init,final,inc)))
mshsayem
  • 17,557
  • 11
  • 61
  • 69
  • 2
    it is prefered to use the `open` function with the `with/as` statement. It will close the file for you -- even if an exception occured -- which you missed in your code snippet. – Peter Varo Aug 20 '13 at 01:04