상세 컨텐츠

본문 제목

File

Python

by techbard 2016. 6. 13. 09:50

본문

반응형

 

import random
import os

### file write, read, delete if exist

def main():
    # with as를 사용하면 파일을 사용한 뒤 자동으로 파일 객체를 닫음
    with open('my_file.txt', 'w') as f:
        for _ in range(10):
            f.write('a' * random.randint(0, 100))
            f.write('\n')

    lens = [len(x) for x in open('my_file.txt')]
    print(lens)

    if os.path.exists('my_file.txt'):
        os.remove('my_file.txt')
        print('my_file.txt deleted')
    else:
        print('The file does not exist')

if __name__ == '__main__':
    main()
 
 #결과
 [74, 61, 90, 58, 97, 35, 11, 4, 6, 26]
my_file.txt deleted

 

import os

### 줄단위로 Read, Write

def main():
    ls = ['안녕\n', '세계\n']

    with open('hello.txt', 'w') as f:
        f.writelines(ls)

    with open('hello.txt', 'r') as f:
        rls = f.readlines()
        print(rls)

    print('=' * 10)

    # for loop로 줄 단위 읽기
    with open('hello.txt', 'r') as f:
        for l in f:
            print(l.strip('\n'))

    if os.path.exists('hello.txt'):
        os.remove('hello.txt')
        print('my_file.txt deleted')
    else:
        print('The file does not exist')

if __name__ == '__main__':
    main()

#결과
['안녕\n', '세계\n']
==========
안녕
세계
my_file.txt deleted

 

반응형

관련글 더보기

댓글 영역