[英]How to delete all characters after a “==” in each line of a file and update the file, using python script?
I have a huge list of python packages that had been installed saved with the version numbers in the file "foo.txt", I want to delete the "==" and whatever after that in each lines, and save the file.我有一个庞大的 python 软件包列表,这些软件包已安装并保存在文件“foo.txt”中的版本号,我想删除每行中的“==”以及之后的任何内容,然后保存文件。
example text in the file:文件中的示例文本:
autopep8==1.5.3
beautifulsoup4==4.8.2
bleach==3.1.4
bumpversion==0.5.3
... etc
Use the below code.使用下面的代码。
read that file and store it in list named pkg_list.读取该文件并将其存储在名为 pkg_list 的列表中。
output_lst = []
with open("input.txt", "r") as f:
input_data = f.readlines()
output_lst = [name.split("==")[0] for name in input_data]
with open("input.txt", "w") as f:
for pkg in output_lst:
f.write("{}\n".format(pkg))
Use this line of code if you want to create a new file with updated data, if you want to just read use the data then make changes accordingly.如果您想创建一个包含更新数据的新文件,请使用这行代码,如果您只想读取数据,请相应地进行更改。
def read_write_file(input_path, output_path):
with open(input_path, "r") as input_file:
content = input_file.readlines()
with open(output_path, 'w') as output_file:
for line in content:
line = line[:line.find('==')]
output_file.write(line + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.