python的write和writelines有什么区别

Python031

python的write和writelines有什么区别,第1张

Python中Write和Writelines区别如下:

1、参数

file.write(str)的参数时一个字符串,就是你要写入文件的内容。

file.writelines(sequence)的参数可以是一个字符串,也可以是一个字符串序列,比如一个列表,它会迭代帮助你写入文件。

2、格式

文件.write(str)。

文件.writelines(str)。

3、用法

write(str):把字符串写入文件,单行写入。

writelines(str):把字符串按行写入文件,多行写入。

4、具体用法

write函数

f = open("C:/.../示例.txt", 'w',encoding = 'utf-8')

#通过绝对路径打开文件,如果不存在会重新创建一个文件如果存在会覆盖原文件,encoding表示编码结构。

a = 'Life is short!'

f.write(a)

f.close()

#需要注意的是,write中的参数一定要是str类型的

writelines函数

f = open("C:\...\a.txt", 'w',encoding = 'utf-8')

text = ['Life is short\n','I choose python\n','With great power, comes great

responsibility']

f.writelines(text)

f.close()

pythonwrite命令文字方向为左方法如下

一个点上的中心文本(例如在[0,0]处的原点),在X维中,可以使用align=center关键字参数为***.write()。要获得沿着Y维对齐,你需要的字体大小稍微调整:

from turtle import Turtle, Screen

FONT_SIZE = 50

FONT = ("Arial", FONT_SIZE, "bold")

yertle = Turtle()

# The turtle starts life in the center of the window

# but let's assume we've been drawing other things

# and now need to return to the center of the window

***.penup()

***.home()

# By default, the text prints too high unless we roughly

# readjust the baseline, you can confirm text placement

# by doing ***.dot() after ***.home() to see center

***.sety(-FONT_SIZE/2)

***.write("I AM HERE", align="center", font=FONT)

***.hideturtle()

screen = Screen()

***.exitonclick()

不过,如果你不是要开始从中心打印(您的文章是不明确),你可以改变align=center到align=left,或者完全忽略关键字参数align。