Python Files

  • reading the file means accessing the file's data
  • writing to the file means adding or changing data in the file
  • os.path.join() builds the file path for you so it will work on multiple operating systems
    • import os
      os.path.join('Users', 'bob', 'st.txt')
      gives 'Users\\bob\\st.txt' on Windows machine and 'Users/bob/st.txt' on a Mac

Opening and Closing

  • can open a file in three modes
    • 'r' reading only
    • 'w' writing only
    • 'w+' reading and writing
  • open([file_path], [mode])
    • example:
     st = open('st.txt', 'w')
     st.write('hi from Python!')
     st.close()
    • it creates the file if it doesn't exist
    • must close files that you open file_name.close()
  • Option 1: 'with statement'
    with open([file_path], [mode]) as [variable_name]:
         [your_code]
    • it automatically closes the file when it finishes
    • access file by variable_name.what_you_want_to_do
      • example:
        with open('st.txt'. 'r') as file:
          print(file.read())
      • example:
        with open('my_data.txt') as file:
          for line in file:               # reads in one line at a time
              line = line.strip()         # strips newlines
              print(line)                 # or do whatever else you want with it
  • Option 2: skip 'with' and open directly --- newer more shorthand way of doing it
    for line in open([file_path]k, [mode]):
        [your code]
    • doesn't automatically close file
  • can only read a file once when you open it so make sure to save it's contents in a variable or container if need to use them later
  • files are automatically closed when program is done

CSV Files

  • stands for comma separated values
  • every line represents a row in a spreadsheet
  • piece of data separated by a delimiter represents a cell
  • writing example:
    import csv
    
    with open('st.csv', 'w') as f:
      write = csv.writer(f, delimiter = ',')
      write.writerow(['one', 'two', 'three'])
      write.writerow(['four', 'five', 'six'])
    
    will create the file st.csv
    • in a text editor it will look like:
      one, two, three
      four, five, six
    • in a spreadsheet:
      ____________________
      |one  |two  |three |
      ____________________
      |four |five | six  |
      ____________________
  • reading example:
    import csv
    
    with open('st.csv', 'r') as f:
      r = csv.reader(f, delimiter = ',')
      for row in r:
          print(','.join(row))
    adds commas between each piece of data so it appears as it does in the original file
    one, two, three
    four, five, six

Copyright © 2022