问题描述
所以我一直在学习有关Python的课程,而正在教书的讲师并没有真正解释一些东西。
例如,我要显示的代码有一行; f.write("This is line %d\r\n" % (i+1))
。他只是跳到下一部分,并且不解释代码行(有时)(%d,\r\n,
等)。有时候,这就是我“学习”一种语言,甚至不能解释某些行的方式。
我希望有人向我解释一下。
代码:
#
# Read and write files using the built-in Python file methods
#
def main():
# Open a file for writing and create it if it doesn't exist
f = open("textfile.txt","w+")
# write some lines of data to the file
for i in range(10):
f.write("This is line %d\r\n" % (i+1)) ## LINE OF CODE I want explained. (I kNow what write() is)
# close the file when done
f.close()
# Open the file back up and read the contents
f = open("textfile.txt","r")
if f.mode == 'r': # check to make sure that the file was opened
fl = f.readlines() # readlines reads the individual lines into a list
for x in fl:
print (x)
if __name__ == "__main__":
main()
解决方法
%d或多或少为要格式化为字符串的数字指定一个占位符。 \ r \ n是转义序列,几乎只是告诉字符串执行某个命令。即\ r返回并且\ n插入新行。
因此写行告诉您的程序在%d处插入(i + 1),然后在其后直接插入return和换行符。
,f.write()基本上写入您在第一行中打开的文本文件。 write()函数中的参数是要写入文件的字符串。在此示例中,有一个循环显示“ This is line”,然后显示其行号。