0

I would like to create a string:

"FILE1 blabla2\nFILE2 blabla4 ..."

and save it in a file. Please note that, in each line of the file the second integer is the double of the first. At the end it should look like:

FILE1 blabla2
FILE2 blabla4
...

but because I have a big amount of lines of this pattern, it is inefficient to do it manually. I would like to use python for this purpose. I can imagine it could be probably done somehow with:

join()

but I don't know exactly how. Any help is appreciated.

5 Answers 5

3

Assuming you have an upper limit for the numbers, you can do something like.

>>> "\n".join(["FILE{} blabla{}".format(x, x*2) for x in xrange(1, 10)])
'FILE1 blabla2\nFILE2 blabla4\nFILE3 blabla6\nFILE4 blabla8\nFILE5 blabla10\nFILE6 blabla12\nFILE7 blabla14\nFILE8 blabla16\nFILE9 blabla18'

and then just write these to a file using.

with open('random.txt', 'a') as f:
    f.write("\n".join(["FILE{} blabla{}".format(x, x*2) for x in xrange(10)]))
Sign up to request clarification or add additional context in comments.

Comments

1
n_lines = 2 # Actual number of lines you want

output = "\n".join(["FILE{} blabla{}".format(x, x*2) for x in xrange(1, n_lines+1)])

file = open("your_output_file", "w")

for line in output.split("\n"):
    file.write("{}\n".format(line))
file.close()

Comments

1

You can either do that in (almost) one statement:

with open("blabla.txt", "w") as bla:
    bla.write("\n".join("FILE%d blabla%d" % (i, i*2) for i in range(1, 5)))

or you can prepare your list of blabla if you need to reuse it later on:

blabla = ["FILE%d blabla%d" % (i, i*2) for i in range(1, 5)] 
with open("blabla.txt", "w") as bla:
    for item in blabla:
        print >> bla, item # Note that this syntax add the new line without using "\n".join

Comments

1
list_of_strings = [] 
for i in range(3):
    list_of_strings.append("FILE{0} blabla{1}".format(i, i*2))  # or whatever you need

'\n'.join(list_of_strings)

Comments

0

I'll give you hints from which you can figure out very easily:

https://wiki.python.org/moin/ForLoop

https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.