Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何将字符串插入.txt文件中的特定位置?_Python - Fatal编程技术网

Python:如何将字符串插入.txt文件中的特定位置?

Python:如何将字符串插入.txt文件中的特定位置?,python,Python,我有一个.txt文件,其中包含一个名为id= 如何编写一个脚本,查看该.txt文件,找到id=并在后面插入一个字符串= 我有一个单独的名为dictionary的.py文件,其中包含一个dictionary,用于查找和替换.txt文件中的某些单词 我也可以用这本字典作为查找和插入的一种方式吗?逐行读取文件,如果行具有“id=”将其替换为str的内置替换方法,并写入新行,否则写入旧行 使用openpath_to_文件作为fp: 使用openpath_到_新_文件,“w”作为nfp: 字符串=随便什么

我有一个.txt文件,其中包含一个名为id=

如何编写一个脚本,查看该.txt文件,找到id=并在后面插入一个字符串=

我有一个单独的名为dictionary的.py文件,其中包含一个dictionary,用于查找和替换.txt文件中的某些单词


我也可以用这本字典作为查找和插入的一种方式吗?

逐行读取文件,如果行具有“id=”将其替换为str的内置替换方法,并写入新行,否则写入旧行

使用openpath_to_文件作为fp: 使用openpath_到_新_文件,“w”作为nfp: 字符串=随便什么 对于fp中的行: 如果id=in行: new_line=line.replaceid=,fid={string} printfreplaceing{line}与{new_line} nfp.writenew_线 其他: 写线
简短回答:您需要再次读取整个文件,在解析id=时插入新数据,然后再次写入该文件。将python模块命名为dictionary.pysee不是一个好主意。