### Thread: Printing a loop to a file

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2013
Posts
2
Rep Power
0

#### Printing a loop to a file

Hi,
I am completely new to Python.
I wish to print
PHP Code:
 \begin{figure}[h] \centering \includegraphics[scale=0.15]{DSC_0001.jpg} \end{figure}  
to a file. But with it also in a loop so that the image number will increase by one each time. So something like,
PHP Code:
 for x in range (1,100): print("\begin{figure}[h]") print("\centering") print("\includegraphics[scale=0.15]{DSC_000"x".jpg}") print("\end{figure}")  
I can't even get this bit to work, so the next stage of writing this to file will be the next step.
Do I then need to have a file already created or by writing to a file will it be created?
Any help would be greatly appreciated,
Thanks,
Shane
2. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2013
Location
Posts
51
Rep Power
5
Originally Posted by ofey
Hi,
I am completely new to Python.
I wish to print
PHP Code:
 \begin{figure}[h] \centering \includegraphics[scale=0.15]{DSC_0001.jpg} \end{figure}  
to a file. But with it also in a loop so that the image number will increase by one each time. So something like,
PHP Code:
 for x in range (1,100): print("\begin{figure}[h]") print("\centering") print("\includegraphics[scale=0.15]{DSC_000"x".jpg}") print("\end{figure}")  
I can't even get this bit to work, so the next stage of writing this to file will be the next step.
Do I then need to have a file already created or by writing to a file will it be created?
Any help would be greatly appreciated,
Thanks,
Shane
The backslashes are creating escape characters. You'll need to either create raw strings with an r before the strings: r"string". Or double up the backslashes.
as for saving to a file, there are many different ways. The simple way is:
Code:
x = open('textfile.txt', 'w') #first argument is any filename and second is the file mode. w = write.
x.write('write stuff here')
x.close() #or x.flush() if you want to send it to file but keep writing.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jul 2013
Posts
2
Rep Power
0
Ok I figured outt he first bit,
Code:
for x in range (1,103):
print("\\begin{figure}[h]")
print("\\centering")
if x < 10:
print("\\includegraphics[scale=0.15]{DSC_000"+str(x)+".jpg}")
if ((x > 9) & (x < 100)):
print("\\includegraphics[scale=0.15]{DSC_00"+str(x)+".jpg}")
if x > 99:
print("\\includegraphics[scale=0.15]{DSC_0"+str(x)+".jpg}")
print("\\end{figure}")
Now I've to try to write it to a file.