GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — learn/doc/python_os_io at main · gyuho/learn

Expand file tree

/

python_os_io

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
/

python_os_io

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
code
code
 
 
README.md
README.md
 
 

README.md

Outline

back to contents

Python: os, io

  • read file
  • write file
  • write csv

↑ top




read file

#!/usr/bin/python -u

if __name__ == "__main__":

    f = open('../README.md')
    print f.read()

↑ top




write file

#!/usr/bin/python -u
import os

if __name__ == "__main__":

    fpath = "test.txt"

    f = open(fpath, 'w')
    f.write("Hello World!")
    f.close()

    f = open(fpath)
    print f.read()
    # Hello World!

    os.remove(fpath)

↑ top




write csv

#!/usr/bin/python -u
import csv
import os

if __name__ == "__main__":

    fpath = "test.csv"
    columns = ["A", "B", "C"]

    data1 = {}
    data1["A"] = "Google"
    data1["B"] = "Facebook"
    data1["C"] = "Amazon"

    data2 = {}
    data2["A"] = "Google"
    data2["B"] = "Microsoft"
    data2["C"] = "Amazon"
    
    data3 = {}
    data3["A"] = "Amazon"
    data3["B"] = "Facebook"
    data3["C"] = "Google"
    
    data_list = [data1, data2, data3]

    with open(fpath, 'wb') as f:
        w = csv.DictWriter(f, fieldnames=columns, delimiter=',')
        w.writeheader()
        for elem in data_list:
            w.writerow(elem)

    os.remove(fpath)

↑ top




You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.