方法一:readline函数
with open(file_path, 'r') as file:
line = file.readline()
while line:
print(line)
line = file.readline()
方法二:readlines函数
with open(file_path, 'r') as file:
lines = file.readlines()
for line in lines:
print(line)
方法三:for循环直接读取
在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据:
with open(file_path, 'r') as file:
for l in file:
print(l)
而在Python 2.1里,你只能用xreadlines迭代器来实现
方法四:用fileinput模块
import fileinput
for line in fileinput.input("sample.txt"):
print(line)
例如用两种方法筛选文件中含有关键字$GNGLLd的行并存储到新的文件中:
# 方法一
def extract_lines_with_keyword(file_path, keyword):
extracted_lines = []
with open(file_path, 'r') as file:
lines = file.readlines()
for line in lines:
if keyword in line:
extracted_lines.append(line[line.index(keyword):])
return extracted_lines
file_path = r'C:\Users\KONG\Desktop\922.nma' # 输入文件路径
keyword = '$GNGLL'
extracted_lines = extract_lines_with_keyword(file_path, keyword)
output_file_path = r'C:\Users\KONG\Desktop\ot.nma' # 输出文件路径
with open(output_file_path, 'w') as output_file:
for line in extracted_lines:
output_file.write(line)
# 方法二
def extract_lines_with_keyword(file_path, keyword):
extracted_lines = []
with open(file_path, 'r') as file:
for l in file:
if keyword in l:
extracted_lines.append(l[l.index(keyword):])
return extracted_lines
file_path = r'C:\Users\KONG\Desktop\922.nma' # 替换为你的输入文件路径
keyword = '$GNGLL'
extracted_lines = extract_lines_with_keyword(file_path, keyword)
output_file_path = r'C:\Users\KONG\Desktop\op.nma' # 替换为你想要输出的文件路径
with open(output_file_path, 'w') as output_file:
for line in extracted_lines:
output_file.write(line)