0

What I Want:

  • write lines to file
  • simply code
  • It's ok if code don't need argv or some others

    Here is my code:

    from sys import argv
    
    script, file_name = argv
    
    target = open(file_name, 'w')
    
    while True:
        line = raw_input()
        target.write(line)
        target.write("\n")
        if line.strip() == '':
            break
    

I found two question about it, but I'm a new learner with Python and I don't know how to combine the logic from the answers in these related questions.

write multiple lines in a file

Raw input across multiple lines

Hope I express clearly.Thanks.

Community
  • 1
  • 1
WillBC
  • 83
  • 2
  • 9

2 Answers2

1

Your code will work but if you want to use writelines and the iter logic from both linked questions, you can use a for loop with iter(raw_input,"") which will loop until an empty string:

from sys import argv
script, file_name = argv

with open(file_name, 'w') as f:
    f.writelines(line+"\n" for line in iter(raw_input,""))

iter(raw_input,"") behaves link an infinite while loop, it will keep asking for input until the user just hits return, file.writelines takes an sequence of strings to write which we pass using a a generator expression.

If you were to use file.write, you just loop over the iter(raw_input, "") again and write in the loop:

with open(file_name, 'w') as f:
    for line in iter(raw_input, ""):
        f.write(line+"\n")
Community
  • 1
  • 1
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
-1

if you want to only write then this code should be fine.This code takes the file name from user and then writes the data into file line by line. Execution stops when there is no data entered by user.

file_name = raw_input("Enter the file name")
target = open(file_name, 'w')
while True:
     line = raw_input("enter data")
     target.write(line)
     target.write("\n")
     if line.strip() == '':
         break
target.close()
Denis
  • 1,219
  • 1
  • 10
  • 15