Blog 7: File Handling For Hackers

File handling is one of the most powerful features in Python, and it's an essential skill for hackers. Whether you're automating log analysis, extracting credentials, writing payloads, or storing your own data, understanding how to read, write, and manipulate files can give you an edge in scripting and automation.


1. What is File Handling?

File handling in Python allows you to create, read, write, and delete files stored on your computer. The built-in open() function is your main tool to work with files.

Syntax:

file = open("filename", "mode")

Modes:

Mode Description
"r" Read mode (default)
"w" Write mode (overwrites existing file)
"a" Append mode (adds to existing file)
"b" Binary mode (for non-text files)/td>
"x" Create file, returns error if file exists

2. Reading from a File

Reading is the most common file operation in hacking (e.g., reading config files, wordlists, logs).

Example:

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

Better Practice Using with:

with open("example.txt", "r") as file:
  content = file.read()
  print(content)

Other Useful Methods:

readline()   # Reads a single line
readlines()  # Reads all lines as a list

3. Writing to a File

Writing allows you to save data, logs, reports, or payloads.

Example:

with open("log.txt", "w") as file:
  file.write("[INFO] Script executed successfully!\n")
  • Note: Using "w" overwrites the file.
  • To append, use "a":
with open("log.txt", "a") as file:
  file.write("[WARNING] New entry added.\n")

4. Creating a File

To create a file, use mode "x". This will throw an error if the file already exists:

with open("newfile.txt", "x") as file:
  file.write("This is a newly created file.")

5. Checking if a File Exists

Python provides tools to prevent errors using the os and pathlib modules.

Using os.path:

import os
if os.path.exists("example.txt"):
  print("File exists")
else:
  print("File not found")

6. Reading Files Line-by-Line (Useful for Wordlists)

This is especially useful in password brute-force scripts:

with open("wordlist.txt", "r") as file:
  for line in file:
      password = line.strip()
      print(f"Trying password: {password}")

7. Deleting Files

You can also delete files if needed:

import os
os.remove("log.txt")

To avoid exceptions:

if os.path.exists("log.txt"):
  os.remove("log.txt")

8. Use Case for Hackers: Log File Parser

with open("access.log", "r") as file:
  for line in file:
      if "404" in line:
          print("[!] Found 404 Error:", line.strip())

You can combine file reading with regex or string matching to build your own log analyzers.


9. Best Practices

  • Always close files or use with for auto-close.
  • Use exception handling (try-except) to manage file errors.
  • Validate file paths before accessing.
  • Strip newlines when reading lines (.strip()).

10. Key Takeaways

  • Use open() with modes like r, w, a, x.
  • Use with open() to manage resources better.
  • Handle file existence using os.path.exists().
  • Combine file handling with logic for automation, brute-forcing, parsing, etc.

Comments