Python: Data Files

  1. Introduction to Python
  2. Python: Choosing a Text Editor or IDE
  3. Python: Hello World
  4. Python: Variables, Strings and Numbers
  5. Python: Variable Naming
  6. Python: Math, Familiar
  7. Python: Math, Less Familiar
  8. Python: Mathematical Order of Operations
  9. Python: Introducing PEP 8
  10. Python: Text Concatenation
  11. Python: if Statements and Comparison Operators
  12. Python: else and elif statements
  13. Python: Testing Multiple Conditions
  14. Python: Testing Sets of Conditions
  15. Python: Nested if Statements
  16. Python: Lists
  17. Python: Adding To and Changing Lists
  18. Python: Lists: Take a Slice, Delete Elements, Popping Elements
  19. Python: Tuples
  20. Python: for Loops
  21. Python: Nested for Loops
  22. Python: Capturing and Formatting User Input
  23. Python: Dictionaries
  24. Python: Functions
  25. Python: While Loops
  26. Python: Creating and Using Classes
  27. Python: Data Files
  28. Python: Modules
  29. Python: CSV Files
  30. Python: JSON Files
  31. Python: Errors and Exception Handling
  32. Python: Using Pexpect
  33. Python : Using Pexpect :
  34. Python : Using Pexpect:
  35. Python: DCL Conversion to Python

Go to Chapter 62 of A Smarter Way.

In Python, you don’t handle files directly. Instead you create a file handle, which opens the file either read-only or read-write. It is important to close the file when you are done!

The with syntax takes care of both opening and closing the file for you. This example opens the file for writing (“w”):

with open("some_filename.txt", "w") as file_handle:

or more conventionally:

with open("data.txt", "w") as f:

Yes, lots of people simply refer to the file as f, because the whole object is going to come and go quickly, in most cases. Don’t ask me how that’s PEP8 compliant.

If you are opening as read-only:

with open("data.txt", "r") as f:

And be especially careful when you want to append data -meaning you want to keep existing data:

with open("data.txt", "a") as f:

You’ll recognize the syntax so far: a statement followed by a colon character. We’re going to dive into an indent here, and do things with the file until we’re done:

with open("data.txt", "w") as f:
    #write to the file:
    f.write("Joe Jackson ID:123456")
    #read one line at a time:
    line = f.readline()
    # Read all lines in the file, as a list:
    lines = f.readlines()
#and from here we're out of the with statement 
Now go to this page, read it, and remember how to get back to it. 😉