18_Python之文件讀取

文件讀取(Python語言實現)

1. 讀取整個文件 read()

fn = 'test.txt'
file_obj = open(fn, encoding='UTF-8')
data = file_obj.read()
file_obj.close()  # 不關閉會對文件造成不必要的損害
print(data)

2. with 關鍵詞

fn = 'test.txt'
with open(fn, encoding='utf-8') as file_obj:
    data = file_obj.read()
    print(data.rstrip())  # 輸出時刪除末端字符

3. 逐行讀取文件

# 逐行讀取文件內容
fn = 'test.txt'
with open(fn, encoding='utf-8') as file_obj:
    for line in file_obj:  # 逐行讀取文件到變量line
        print(line)  # 有空行

image.png

# 逐行讀取文件內容
fn = 'test.txt'
with open(fn, encoding='utf-8') as file_obj:
    for line in file_obj:  # 逐行讀取文件到變量line
        print(line.rstrip())  # 沒有空行

image.png


4. 逐行讀取使用 readlines()

使用with關鍵詞配合open時,所打開的文件對象當前只在with區塊內使用,使用readlines() 進行逐行讀取,同時以列表的形式存儲,換行字符也會被存儲進去。

fn = 'test.txt'
with open(fn, encoding='utf-8') as file_obj:
    obj_list = file_obj.readlines()  # 每次讀一行
print(obj_list)

image.png

逐行輸出列表內容:

fn = 'test.txt'
with open(fn,encoding='utf-8') as file_obj:
    obj_list = file_obj.readlines()  # 每次讀取一行
for line in obj_list:
    print(line.rstrip())  # 打印列表

image.png


5. 數據組合

# 文檔在一行顯示
fn = 'test.txt'
with open(fn, encoding='utf-8') as file_obj:
    obj_list = file_obj.readlines()
str_obj = ''  # 先設爲空字符
for line in obj_list:
    str_obj += line.rstrip()
print(str_obj)

image.png


6. 字符串的替換

使用Word時有查找和替換功能,Python也有這個方法使新的字符串取代舊字符串。

fn = 'test.txt'
with open(fn, encoding='utf-8') as file_obj:
    data = file_obj.read()
    new_data = data.replace('的', 'blueheart')
    print(new_data.rstrip())

image.png


7. 數據的搜索

Word有搜索和功能,使用Python使這類工作變得簡單。

# 數據的搜索
fn = 'test.txt'
with open(fn,encoding='utf-8') as file_obj:
    obj_list = file_obj.readlines()

str_obj = ''  # 先設爲空字符
for line in obj_list:
    str_obj += line.rstrip()

findstr = input("請輸入要搜索的字符串:")
if findstr in str_obj:
    print("搜索 %s 字符串在 %s 文件中" % (findstr, fn))
else:
    print("搜索 %s 字符串不在 %s 文件中" % (findstr, fn))

image.pngimage.png


8. 使用 find() 進行數據搜索

就多了一句話:index = str_obj.find(findstr)  # 第11行

# 使用find(), 可以得到查詢字符 索引位置
fn = 'test.txt'
with open(fn,encoding='utf-8') as file_obj:
    obj_list = file_obj.readlines()

str_obj = ''  # 先設爲空字符
for line in obj_list:
    str_obj += line.rstrip()

findstr = input("請輸入要搜索的字符串:")
index = str_obj.find(findstr)  # 就多了一個索引
if findstr in str_obj:
    print("搜索 %s 字符串在 %s 文件中" % (findstr, fn))
    print("在索引 %s 位置出現 " % index)
else:
    print("搜索 %s 字符串不在 %s 文件中" % (findstr, fn))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章