-1

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.

example text in the file:

autopep8==1.5.3
beautifulsoup4==4.8.2
bleach==3.1.4
bumpversion==0.5.3
... etc

2 Answers2

-1

Use the below code.

read that file and store it in list named 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))
Astik Gabani
  • 599
  • 1
  • 4
  • 11
-1

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')
Kuldeep Singh
  • 199
  • 1
  • 11
  • tried but not changing anything, can you explain your code please – Older version of me Jun 28 '20 at 08:08
  • how are you calling this? you need to call read_write_file functions with two arguments: 1. input file path (absolute path), 2. Absolute file name where exactly you want to save after change. Explanation: First with is opening you input file in read mode and keeping all your input lines in 'content' variable. Second with is opening file in write mode. for loop is iterating over all lines in content and then next line is slicing line from index 0 to index of '==' and assigning it back to line. Then next line is writing line to output file. (line.find with return you start index of '=='). – Kuldeep Singh Jun 29 '20 at 19:11
  • make sure paths are files not the directories and absolute paths. – Kuldeep Singh Jun 29 '20 at 19:12