Search code examples
pythonformattingfwrite

Cannot understand write() formatting (how it works)


So I've been taking a course on Python and the instructor that is teaching doesn't really explain somethings.

For example, the code I'm about to show has a line; f.write("This is line %d\r\n" % (i+1)). He just jumps right to the next part and doesn't explain the line of code (sometimes) (the %d, \r\n, etc.). This is how sometimes I "learn" a language and cannot even explain some lines.

I would like someone to explain to me what it does.

Code:

#
# 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()

Also, if someone coulde link me to a page explaining all of this. Thanks.


Solution

  • %d more or less specifies a placeholder for a number to be formatted into the string. \r\n are escape sequences, pretty much just telling the string to do a certain command. I.e. \r is return and \n inserts a new line.

    So that write line is telling your program to insert (i+1) at %d and then insert a return and new line directly after.