Python從txt檔案中逐行讀取資料

2021-08-31 01:13:16 字數 986 閱讀 3728

# -*-coding:utf-8-*-

import os

for line in open("./samples/label_val.txt"):

print('line=', line, end = '') #後面跟 , end = ''將忽略換行符

#line= ./samples/images/3-3_5460e99f0ca9c410960571e02a0d273c.bmp

#line= ./samples/images/5-5_f391afef5c574a0659039595a038ef92.bmp

#line= ./samples/images/2-2_518e32236467c850a268ed2ec1d68697.bmp

'''file_obj = open("./samples/label_val.txt")

all_lines = file_obj.readlines() #讀取全部內容

for line in all_lines:

print('line=', line)

file_obj.close()

# 寫之前,先檢驗檔案是否存在,存在就刪掉

if os.path.exists("./samples/label_val.txt"):

os.remove("./samples/label_val.txt")

mylist = ["luoluo", "taotao", "mumu"]

# 以寫的方式開啟檔案,如果檔案不存在,就會自動建立

file_write_obj = open("./samples/label_val.txt", 'w')

for var in mylist:

file_write_obj.writelines(var)

file_write_obj.write('\n')

file_write_obj.close()

'''

python逐行讀寫txt檔案

coding utf 8 import os file obj open test2.txt all lines file obj.readlines for line in all lines print line file obj.close 寫之前,先檢驗檔案是否存在,存在就刪掉 if os....

python逐行讀取txt檔案時出現多餘空行的問題

這幾天做程式作業的時候需要用python的讀取檔案功能,在我用readlines 函式做逐行讀取的時候遇到了乙個小問題,在這裡和大家分享一下。txt檔案裡的內容是這樣的 1 1 2 23 3 4 45 5 也沒什麼問題 1 with open 001.txt r as f 2 lines f.rea...

Python 逐行分割大txt檔案的方法

如下所示 coding import io limit 150000 file count 0 url list with io.open d db new bak db new 20171009 bak.sql r encoding utf 16 as f for line in f url li...