"Anything else expression" in Python - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: "Anything else expression" in Python (/thread-11067.html) |
"Anything else expression" in Python - spedy93 - Jun-21-2018 Hello, I´m new in programming, I am trying to erase something from the lines of a file, example: file is made of to colums: xxxx zzzz aaaa tttt dddd nnn I want to erase the second colum, what I am trying to do is to use the replace funtion, like this: (there a common pattern it is " XXXX" two spaces and the letters beyond). my code is something like this: var1=(" *") var2=("---") f = open("archive.txt",'r') change = f.read() change = change.replace(var1,var2) f.close() new = open("newarchive.txt",'w') new.write(change) new.close() the problem is the regular expression I am using " var1=(" *") " " *" it is not working it does no match my lines, I have tried literally everything I found in internet but no luck if I try: var1=(" ") var2=("---") f = open("archive.txt",'r') change = f.read() change = change.replace(var1,var2) f.close() new = open("newarchive.txt",'w') new.write(change) new.close() it replace only the two spaces with --- "xxxx---zzzz" and I need only the "xxxx---" with out the text beyond (zzzz) what regular expression match " something" (spaces plus some alphanumeric text?) ? thanks for your time. RE: "Anything else expression" in Python - wavic - Jun-21-2018 For example: >>> data="""xxxx zzzz ... aaaa tttt ... dddd nnn""" >>> new_data = [] >>> for line in data.split('\n'): ... new_data.append(f"{line[:line.index(' ')]}\n") ... >>> new_data ['xxxx\n', 'aaaa\n', 'dddd\n'] # move the cursor at the beginning of the file >>> file_object.seek(0) # the file should be open in 'r+' mode ( reading and writing ) >>> file_object.writelines(new_data) |