学习笔记python-修改txt配置文件的指定行

1、需求:用python写一些测试工具的时候,经常需要修改一些简单的配置数据,这些配置数据用数据库或者CSV,Excel都比较麻烦,可以存为txt文件,每行一个参数,修改比较方便。
2、config.txt配置文件内容:

0.1
120
0.2
118
0.3
119
0.4
121

3、配置数据读取,用pandas将txt数据读入DataFrame,再指定坐标进行提取

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:用空格分隔每行的数据,这里只有1列,可以不设置
#index_col=0:可设置第1列数据作为index,这里只有1列,所以不设置
print(data[0][0])  #取第1个数据,第0列第1行,结果是0.1

4、修改指定参数

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为新参数,记得加换行符\n
with open(my_file, 'w',encoding='utf-8') as file:
    file.writelines( lines )

修改结果:

0.1
120
0.2
new
0.3
119
0.4
121
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容