K. Caleb Wang

File Input/Output Examples

File Input/Output Basics: Bash and Python

 

Bash

### file name: output.sh
# purpose: output two lines to a file
# usage: bash output.sh

# output to a new file, a.txt, with >
echo "first line" > a.txt
# append to a file, a.txt, with >>
echo "second line" >> a.txt

# alternatively, use \n to make the next line and output to a new file, ex.
# printf "first line\nsecond line\n" > a.txt
### file name: input-output.sh
# purpose: input from an existing file, a.txt, and then output to another file, b.txt
# usage: bash input-output.sh

# output to a new file, b.txt, with >
cat a.txt > b.txt
# append to a file, b.txt, with >>
cat a.txt >> b.txt

How to run:

Open a terminal and type    bash output.sh    , then hit enter. Run input-output.sh in a similar way.

Python

### file name: output.py
# purpose: output two lines to a file
# reference: https://docs.python.org/3/tutorial/inputoutput.html
# usage: python output.py

# open a file object with a 'w'ritable file, a.txt
# the opened file object will be closed at the end of the 'with' statement
# use \n to make the next line
with open('a.txt','w') as file:
    aa = 'first line\n' + 'second line\n'
    file.write(aa)
### file name: input-output.py
# purpose: input from an existing file, a.txt, and then output to another file, b.txt
# reference: https://docs.python.org/3/tutorial/inputoutput.html
# usage: python input-output.py

# open a file object to 'r'ead contents from an existing file, a.txt
# the opened file object will be closed at the end of the 'with' statement
with open('a.txt','r') as file:
    aa = file.read() 
    # open another file object to 'a'ppend contents to a file, b.txt 
    # b.txt will be created if it is not yet existing
    with open('b.txt', 'a') as file:
        file.write(aa)

How to run:

Open a terminal and type    python output.py    , then hit enter. Run input-output.py in a similar way.