Home > Back-end >  Python - Data manipulation in a file
Python - Data manipulation in a file

Time:02-07

I'm at the stage where I've a txt file in the form:

text1;10;20;11
text2;3;4;5
text3;4;5;7

Anyone got any idea what function to use to get rid of the numbers in the middle of each line? I would like to have in output:

text1;11
text2;5
text3;7

Currently I have done:

    for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f:
                content = f.read()
                f.close()
                content1 = re.sub('\t', '', content, flags=re.M)
                content2 = re.sub(' ', '', content1, flags=re.M)
                f = open(ii, "w ")
                f.write(content2)
                f.close()

CodePudding user response:

You can just split the String with the split method and get the first and last element together

s = "text1;10;20;11"
result = s.split(";")[0]   ";"   s.split(";")[-1]

output will be text1;11

CodePudding user response:

To complete Mario Khoury's answer, I'd point out that you don't need to open/close the file you want to read/write to within with open(ii, 'r') as f:.

what do you want to do? Create another file with only the start/end elements of each line, or replace the lines in the original file? File handling depends on what you want to do.

for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f, open(output_file, 'w') as f_out:
                content = f.read()
                res = content.split(";")[0]   ";"   s.split(";")[-1]
                f_out.write(res)

CodePudding user response:

a=['text1;10;20;11','text2;3;4;5','text3;4;5;7']
for i in a:
  s=i.split(';')
  print(s[0]   ';'   s[-1])

Output:

text1;11
text2;5
text3;7

CodePudding user response:

you open the file get the data manipulation it and write the file back

file_name ="/content/untitled" 
list_res=[]
with open(file_name ,"r") as f:
  while True:
    line = f.readline()
    if not line:
      break
    list_t = line.split(";")
    list_res.append(f"{list_t[0]};{list_t[-1]}")
print(list_res)
with open(file_name ,"w") as f:
  f.write("".join(list_res))
  •  Tags:  
  • Related