• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Python | Reading and Writing Files
  1. Writing and reading text files
  2. File existence and properties
  3. Get file information
  4. Writing and reading binary files
  5. Writing and reading JSON files
  6. Writing and reading CSV files

  1. Writing and reading text files
    # import Path class
    from pathlib import Path
    
    # create path object - the path can be relative or absolute
    path = Path('data/file.txt')
    
    try:
      # create parent directory if it doesn't exist
      path.parent.mkdir(parents=True, exist_ok=True)
    
      # write content to file (create/overwrite)
      path.write_text('Hello Python', encoding='utf-8')
    
      # append content to file
      with path.open('a', encoding='utf-8') as f:
        f.write("\n!")
    
      # read content from file
      text = path.read_text(encoding='utf-8')
    
      print(text)
    except FileNotFoundError:
      print("File not found")
    except PermissionError:
      print("Permission denied")
    except Exception as e:
      print(f"An error occurred: {e}")
    Output:
    Hello Python
    !
  2. File existence and properties
    from pathlib import Path
    
    path = Path('data/file.txt')
    
    # check if file exists
    if path.exists():
      print(f'the file \'{path}\' exists')
    else:
      print(f'the file \'{path}\' doesn\'t exists')
    Output:
    the file 'data/file.txt' exists
  3. Get file information
    from pathlib import Path
    
    path = Path('data/file.txt')
    
    print(f'is file: {path.is_file()}')
    print(f'is directory : {path.is_dir()}')
    print(f'file info: {path.stat()}')
    Output:
    is file: True
    is directory : False
    file info: os.stat_result(st_mode=33204, st_ino=17898, st_dev=2080, st_nlink=1, st_uid=1000, st_gid=1000, st_size=14, st_atime=1748889846, st_mtime=1748889817, st_ctime=1748889817)
  4. Writing and reading binary files
    from pathlib import Path
    
    path = Path('data/file.bin')
    
    path.parent.mkdir(parents=True, exist_ok=True)
    
    # write binary data to file (create/overwrite)
    path.write_bytes('Hello Python'.encode('utf-8'))
    
    # read binary data from file
    data = path.read_bytes()
    
    print(data.decode('utf-8'))
    Output:
    Hello Python
  5. Writing and reading JSON files
    Writing/reading to/from a json file:
    from pathlib import Path
    
    # import json module
    import json
    
    # data
    x = { 'a': 1, 'b': 2 }
    y = { 'a': 11, 'b': 22 }
    z = [x, y] # list of dictionaries
    w = { 'r': x, 's': y, 't': z } # dictionary of list, set, and dictionaries
    
    path = Path('data/file.json')
    
    # write JSON to file
    path.write_text(json.dumps(w, indent=2), encoding='utf-8')
    
    # read JSON file
    text_indented = path.read_text(encoding='utf-8')
    
    print(text_indented)
    
    text_json = json.loads(path.read_text(encoding='utf-8'))
    
    print(list(text_json.keys())) # Output: ['r', 's', 't']
    
    print(text_json['t'][0]['b']) # Output: 2
    Output:
    {
      "r": {
        "a": 1,
        "b": 2
      },
      "s": {
        "a": 11,
        "b": 22
      },
      "t": [
        {
          "a": 1,
          "b": 2
        },
        {
          "a": 11,
          "b": 22
        }
      ]
    }
    ['r', 's', 't']
    2
  6. Writing and reading CSV files
    from pathlib import Path
    
    # import csv module
    import csv
    
    data = [
      ['name', 'score'],
      ['a', 10],
      ['b', 15]
    ]
    
    path = Path('data/file.csv')
    
    # write CSV
    with path.open('w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerows(data)
    
    # read CSV
    with path.open('r', encoding='utf-8') as f:
      reader = csv.reader(f)
      # read headers
      headers = next(reader)
      print(f"headers: {headers}")
    
      for i, line in enumerate(reader, 1):
        print(f"line {i}: {dict(zip(headers, line))}")
    Output:
    headers: ['name', 'score']
    line 1: {'name': 'a', 'score': '10'}
    line 2: {'name': 'b', 'score': '15'}
© 2025  mtitek