1、需求:用python寫一些測試工具的時候,經(jīng)常需要修改一些簡單的配置數(shù)據(jù),這些配置數(shù)據(jù)用數(shù)據(jù)庫或者CSV,Excel都比較麻煩,可以存為txt文件,每行一個參數(shù),修改比較方便。
2、config.txt配置文件內(nèi)容:
0.1
120
0.2
118
0.3
119
0.4
121
3、配置數(shù)據(jù)讀取,用pandas將txt數(shù)據(jù)讀入DataFrame,再指定坐標(biāo)進(jìn)行提取
import pandas as pd
data = pd.read_table('D:\\0python\\txt\\config.txt',header=None,encoding='utf-8',delim_whitespace=True,\
#index_col=0,\
)
#header=None:不要每列的column name
#encoding='utf-8':
#delim_whitespace=True:用空格分隔每行的數(shù)據(jù),這里只有1列,可以不設(shè)置
#index_col=0:可設(shè)置第1列數(shù)據(jù)作為index,這里只有1列,所以不設(shè)置
print(data[0][0]) #取第1個數(shù)據(jù),第0列第1行,結(jié)果是0.1
4、修改指定參數(shù)
line_to_replace = 3 #需要修改的行號,3表示第4行
my_file = 'D:\\0python\\txt\\config.txt'
with open(my_file, 'r',encoding='utf-8') as file:
lines = file.readlines()
if len(lines) > int(line_to_replace):
lines[line_to_replace] = 'new\n' #new為新參數(shù),記得加換行符\n
with open(my_file, 'w',encoding='utf-8') as file:
file.writelines( lines )
修改結(jié)果:
0.1
120
0.2
new
0.3
119
0.4
121