write multiple lines in a file in python

前端 未结 8 1830
长情又很酷
长情又很酷 2020-12-03 08:04

I have the following code:

line1 = raw_input(\"line 1: \")
line2 = raw_input(\"line 2: \")
line3 = raw_input(\"line 3: \")
print \"I\'m going to write these          


        
相关标签:
8条回答
  • 2020-12-03 08:10

    You're confusing the braces. Do it like this:

    target.write("%s \n %s \n %s \n" % (line1, line2, line3))
    

    Or even better, use writelines:

    target.writelines([line1, line2, line3])
    
    0 讨论(0)
  • 2020-12-03 08:12
    with open('target.txt','w') as out:
        line1 = raw_input("line 1: ")
        line2 = raw_input("line 2: ")
        line3 = raw_input("line 3: ")
        print("I'm going to write these to the file.")
        out.write('{}\n{}\n{}\n'.format(line1,line2,line3))
    
    0 讨论(0)
  • 2020-12-03 08:15

    this also works:

    target.write("{}" "\n" "{}" "\n" "{}" "\n".format(line1, line2, line3))
    
    0 讨论(0)
  • 2020-12-03 08:18

    another way which, at least to me, seems more intuitive:

    target.write('''line 1
    line 2
    line 3''')
    
    0 讨论(0)
  • 2020-12-03 08:18
    variable=10
    f=open("fileName.txt","w+") # file name and mode
    for x in range(0,10):
        f.writelines('your text')
        f.writelines('if you want to add variable data'+str(variable))
        # to add data you only add String data so you want to type cast variable  
        f.writelines("\n")
    
    0 讨论(0)
  • 2020-12-03 08:25

    I notice that this is a study drill from the book "Learn Python The Hard Way". Though you've asked this question 3 years ago, I'm posting this for new users to say that don't ask in stackoverflow directly. At least read the documentation before asking.

    And as far as the question is concerned, using writelines is the easiest way.

    Use it like this:

    target.writelines([line1, line2, line3])
    

    And as alkid said, you messed with the brackets, just follow what he said.

    0 讨论(0)
提交回复
热议问题