👨‍💻
Hacking Notes
  • Hacking Notes
  • 💅One-Liners
  • ⚔️Offensive
    • Exploit Workflow
    • Recon
      • OSINT
      • DNS
        • Domain Discovery
      • Layer 2 Config and Analysis
      • Port Scanning and Discovery
      • Port Attacks
      • Link it all together
    • Payloads
      • MSFVenom
      • Reverse Shells
    • Websites
      • Enumeration
      • Injection/LFI
      • Session Management
      • Brute Forcing
      • JavaScript & XSS
      • SSRF
      • XXE
      • PHP
    • Password Attacks
      • Brute Forcing
      • Mimikatz
      • Password Cracking
      • Hash Extraction
      • Wordlist Generation
    • Databases
      • SQL
      • Mongodb
    • Microsoft Windows Exploits
      • Enumeration
      • Powershell
      • Cmd
      • Privilege Escalation
      • Active Directory
      • Bloodhound
    • Social Engineering
    • Netcat & Socat
    • File Transfers
    • Metasploit
      • Writing Modules
    • PS Empire
    • Priv Escalation
    • Post Exploitation
    • Pivoting
    • Certs and Secrets
    • NGROK
    • Misc.
  • 🛡️Defensive
    • Defensive Notes
    • Windows Forensics
      • Program Execution Artifacts
      • ASEP Locations
      • Event Logs
    • Linux Forensics
    • Network Forensics
      • tshark
      • Wireshark Filters
    • Memory Forensics
    • Stego
    • Malware Analysis
    • Volatility
  • 🌩️Cloud
    • Scope and Shared Responsibility
    • AWS CLI
    • Azure CLI
    • SaaS Attacks
    • PaaS
  • ⌨️Programming
    • Programming Notes
    • Examples and Quick Scripts
    • PowerShell
    • Pwn
      • Windows Pwn
    • Python
      • Basic Python
      • Modules
      • Working with Files
      • Networking
      • Attack Related
      • Scapy
        • Using Scapy
        • Reading PCAP
    • C
      • Code Examples
      • GDB
    • PHP
Powered by GitBook
On this page

Was this helpful?

  1. Programming
  2. Python

Working with Files

Opening a file with Python we need to close it as well.

# Open a new file object for writing only
myfile = open("/tmp/newfile.txt", "w")

# Use the write method to add data to the file
myfile.write("Here is my message.\n")

# The "\n" must be added to separate lines on the file
myfile.write("Here is my second message.")

# We must close out the file object in order to properly close the object
myfile.close()

Instead, we can use a with codeblock which will automatically handle closing the file once we're done with it.

with open("/tmp/newfile.txt", "r") as myfile:
    for line in myfile:
        print(line)

with open('/tmp/cars.txt', 'r') as cars:
    print(cars.read())

We can read all lines of a file into a list for easy use. We need to strip the newline as well.

def fileList(file):
    with open(file) as f:
        lines = f.readlines()
        clean = [ line.strip() for line in lines ]
    return clean
PreviousModulesNextNetworking

Last updated 2 years ago

Was this helpful?

⌨️