Computer Science/๊ธฐํƒ€

[python] ํ…์ŠคํŠธ ํŒŒ์ผ ์ž๋ฅด๊ธฐ (text file crop)

_cactus 2021. 11. 4. 15:50
๋ฐ˜์‘ํ˜•

#ํŒŒ์ด์ฌ ํ…์ŠคํŠธ ํŒŒ์ผ ๋‚ ๋ฆฌ๊ธฐ #python textfile crop #python textfile delete line

๋‹ค์Œ๊ณผ ๊ฐ™์€ ํ…์ŠคํŠธํŒŒ์ผ์ด ์žˆ๋‹ค๊ณ  ํ•˜์ž
์—ฌ๊ธฐ์„œ ํŠน์ • line ํ˜น์€ ์—ฌ๋Ÿฌ๊ฐœ์˜ line์„ ์ง€์šฐ๊ณ  ์‹ถ๋‹ค๋ฉด..??

์ ˆ๋ฐ˜์„ ๋‚ ๋ ค๋ฒ„๋ฆฌ๊ณ  ์‹ถ๋‹ค๋ฉด??

 

 

line 1 of the text file
line 2 of the text file
line 3 of the text file
line 4 of the text file
line 5 of the text file

๋ฐ˜์‘ํ˜•

 

# 1. ํ…์ŠคํŠธ ํŒŒ์ผ ์ฝ์–ด๋“ค์ด๊ธฐ
# filename์— ํ…์ŠคํŠธํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ string์œผ๋กœ ๋„ฃ์–ด์ค€๋‹ค
filename = './textfile.txt'
text_file = opend(filename).readlines()

# 2. ์ง€์šฐ๊ณ  ์‹ถ์€ line index ๋„˜๋ฒ„ ๋˜๋Š” slicing์œผ๋กœ ์ง€์šฐ๊ธฐ
del text_file[0] # ์ฒซ๋ฒˆ์งธ line ์ง€์šฐ๊ธฐ
del text_file[:10] # ์ฒ˜์Œ๋ถ€ํ„ฐ 10๋ฒˆ์งธ ์ค„๊นŒ์ง€ ์ง€์šฐ๊ธฐ
del text_file[-1] # ๋งˆ์ง€๋ง‰ line ์ง€์šฐ๊ธฐ

# 3. ๋‹ค์‹œ ์“ฐ๊ธฐ 
output_filename = './output_textfile.txt'
f = open(output_filename, "w")  
f.writelines(text)  
f.close()
728x90
๋ฐ˜์‘ํ˜•