본문 바로가기
TensorFlow OpenCV

python file example 개행문자 \r 없애기

by BABEL-II 2019. 10. 5.

How to Remove Carrige Return in Text File using Python.

 

DOS 또는 Windows에서 작성한 text file을 linux에 가져가면,

텍스트 문자열 끝에 '\r'이 추가로 붙어서 간다.

이를 vi에서 제거할 떄는

1,$s/^V^M//

이런 명령으로 제거할 수 있지만, 파일이 많을 때는 이렇게 제거하는 것이 불편하기 때문에 Python으로 코드를 작성해보았다.

iimport os

sdir = '~/darknet/IHCIMGS/img/'

flist = os.listdir(sdir)

for fn in flist:

#print (fn)

if fn[-4:] == '.txt':

fpath = sdir + fn

print(fpath)

text_file = open(fpath, "r")

lines = text_file.readlines()

print(lines)

text_file.close()

text_file = open(fpath, "w")

text_file.writelines(lines)

#for l in lines:

# if l[-1] == '\r' : l = l[:-1]

# text_file.write(l + '\n')

text_file.close()n lines