简体   繁体   中英

Writing multiple lines to a textfile by taking input in python?

Iam trying to write a python script that will let me write C code directly to a textfile and change its extension to ".c" without me creating one manually. This is what i did so far..

import time as t
from os import path

def create_C(dest):

    date=t.localtime(t.time())                #getting current system date
    name=raw_input("Enter file name:")+"%d_%d_%d"%(date[0],date[1],date[2])+".c"
                                                            #User enters the filename 

    if not(path.isfile(dest+name)):           #checks if the file already exists
        f=open(dest+name,"w")
        f.write(raw_input("Start Writting:\n"))
        f.close()
    if __name__=='__main__':
        destination='C:\\Users\\Dell\\Desktop\\Puru\
\\python\\intermediate\\createCfile\\'
        create_C(destination)
        raw_input("done")

However this writes only 1 line. How can i get it to write multiple lines?

Instead of calling raw_input once:

f.write(raw_input('Start writing'))

You can call raw_input until an empty string is inserted:

file_content = '\n'.join(iter(raw_input, ''))
f.write(file_content)

Little clearer:

file_lines = iter(raw_input, '') # Get lines as input until an empty line.
file_content = '\n'.join(file_lines) # Join the file lines to one string, seperated by new-line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM