Basic Python

open, readlines, collections, split, read, seek, writer, writerow, close, mode='at'

Naranjito 2021. 5. 6. 11:11

Open the file.

 

1. Open the exist file.

 

  • open('file path', 'open mode')

It returns the objects which has file content. The available modes are 

f=open('/Users/joohyunyoon/Downloads/Book2.xlsx', 'r')

 f <-----------------------.xlsx

⇡                    ⇡                  ⇡

variable  indicating   object

 

2. Read the exist data.

 

  • readlines

 

Return all lines as a list.

 

lines=f.readlines()
lines
>>>
['\ufeffNAVER\n', 'Hyundai\n', 'LG\n', 'Kia']

 

A newline character (\n) is left at the end of the string, and it needed to be ommitted(using strip()).

for line in lines:
    line = line.strip()

 

  • collections

It is container that is used to store collections of data, i.g., list, dict, set, tuple etc.

import collections 
r=open('test.csv',mode='rt')
isinstance(r, collections.Iterable)
>>>
True

 

  • split

Split a string into a list.

txt = "hello,\n my\n name\n is\n Peter, I am 26 years old"
x = txt.split("\n")
print(x)

>>>

['hello,', ' my', ' name', ' is', ' Peter, I am 26 years old']
txt = "welcome to the jungle"
x = txt.split()
print(x)

>>>

['welcome', 'to', 'the', 'jungle']

 

  • read

Read the file by pointer as many as ().

f=open('test.csv',mode='wt',encoding='utf-8')
f.write('python file write')
f.write('newline text \n')
f.write('well done')
f.close()

r=open('test.csv',mode='rt',encoding='utf-8')
r.read(10)
>>>
'python fil'

 

  • seek

Return the pointer to specific point by ().

seek(0) meaning goes back to the first.

r=open('test.csv',mode='rt',encoding='utf-8')
r.seek(0)
>>>
0

 

Write the file.

 

1. Create the empty file.

f=open('/Users/joohyunyoon/Downloads/Book_sell.csv', 'w')

 

  • writer

It returns a writer object which converts the user's data into delimited strings.

 

  • writerow

Write Row, writes a row of data into the specified file.

import csv

f=open('/Users/joohyunyoon/Downloads/sell_list.csv', 'w', encoding='cp949', newline='')
writer=csv.writer(f)
writer.writerow(['name','code','PER'])
writer.writerow(['samsung','005930','15.79'])
writer.writerow(['naver','035420','035420'])
f.close()

 

2. Write something on the empty file.

f.write('SK\n')
>>>
3

f.write('Samsung')
>>>
7

 

  • mode='at'

Appending Text, add file.

a=open('test.csv',mode='at')
a.writelines(['add writeline','not execute inner','\n'])
a.close()

 

3. Close the file.

f.close()