Python Forum
"Anything else expression" in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
"Anything else expression" in Python
#1
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.
Reply
#2
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)
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python beginner that needs an expression added to existing script markham 1 665 Sep-04-2023, 05:24 AM
Last Post: Pedroski55
  Python Regular expression, small sample works but not on file Acernz 5 2,861 Jun-09-2021, 08:27 PM
Last Post: bowlofred
  Using Regex Expression With Isin in Python eddywinch82 0 2,253 Apr-04-2021, 06:25 PM
Last Post: eddywinch82
  New to Python, How does this lambda expression works? Joshh_33 2 1,998 Mar-26-2020, 03:32 PM
Last Post: Joshh_33
  Pass results of expression to another expression cmdr_eggplant 2 2,238 Mar-26-2020, 06:59 AM
Last Post: ndc85430
  Regular expression to fetch comments in C using Python pikkip 4 4,857 Jan-24-2017, 09:21 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020