9 月 252020
 
#定义一个函数,需要传入参数文件名称name和文件内容msg
def text_create(name, msg):
    #定义路径变量并赋值
    desktop_path = 'C://Users/harveymei/Desktop/'
    #定义文件完整路径,路径+文件名称+扩展名后缀
    full_path = desktop_path + name + '.txt'
    #open()函数,打开文件,传入参数为文件完整路径
    #写入模式,如果没有该文件就创建文件,如果有该文件就覆盖写入
    file = open(full_path, 'w')
    #写入传入的参数msg
    file.write(msg)
    #关闭文件
    file.close()
    print('Done')

#调用函数
#创建文件C://Users/harveymei/Desktop/hello.txt,内容为hello world
text_create('hello','hello world')
#创建文件C://Users/harveymei/Desktop/list.txt,内容为中加入换行符实现换行
text_create('list','123456\n654321')
PS C:\Users\harveymei> & C:/Users/harveymei/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harveymei/hello.py
Done
Done
PS C:\Users\harveymei> type .\Desktop\hello.txt
hello world
PS C:\Users\harveymei> type .\Desktop\list.txt
123456
654321
PS C:\Users\harveymei> 

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)