Home > Software design >  Adding items to list, then updating a line based on input
Adding items to list, then updating a line based on input

Time:09-17

Really new to Python, but just struggling on this one aspect. I'm trying to update a list which has lines of data. With one part having True / False. I want to allow the user to input a line number, that they can switch this True to False and False to True.

I have the below so far, which allows me to add the file into the list, but when I try and update it, it comes out as blank. Is anyone able to point me in the right direction please.

list1 = []
with open("myfile.dat", 'r') as fp:
    list1 = fp.readlines()

# Write file
with open("myfile.dat", 'w') as fp:
    hire_out = input("Enter Pos Number")
    for number, line in enumerate(list1):
        if hire_out == True:
            list1[number] = False
            fp.write(list1)

CodePudding user response:

This happens because in Python opening a file in write mode, it will create it if it doesn't exists, and delete everything inside if it exists.

You would have to use open("filename", "a", encoding="utf-8")
This will create the file if it doesn't exists, and add at the end of it's content if it already exists.

CodePudding user response:

There are several problems:

  • if your input file is totally clear, (no other dirty contents, only lines of True and False), you can convert into a boolean list list1 = [True if x.startswith('True') else False for x in list1].
  • hired_out, depended on what you have described, should be a string that can be parsed into an integer, so you should use hire_out = int(input("Enter Pos Number")
  • you dont need enumeration, you only need to use for number in range(len(list1))
  • if the line number is equal to hire_out, you will invert the boolean: should use if hire_out == number: instead of if hire_out == True:
  • you can inverting boolean using list1[number] = not list1[number]
  • after the for loop, the list1 now contains the correct content (of boolean), you can use fp.write('\n'.join([str(x) for x in list1]))

the code should be

list1 = []
with open("myfile.dat", 'r') as fp:
    list1 = fp.readlines()

list1 = [True if x.startswith("True") else False for x in list1]
 
with open("myfile.dat", 'w') as fp:
    hire_out = int(input("Enter Pos Number"))
    for number in range(len(list1)):
        if hire_out == number:
            list1[number] = not list1[number]
    fp.write('\n'.join([str(x) for x in list1]))
  • Related