Home > Mobile >  Slice a given txtfile and write only part of it in a newfile in python
Slice a given txtfile and write only part of it in a newfile in python

Time:07-10

This is my original .txt data:

HKEY_CURRENT_USER\SOFTWARE\7-Zip
HKEY_CURRENT_USER\SOFTWARE\AppDataLow
HKEY_CURRENT_USER\SOFTWARE\Chromium
HKEY_CURRENT_USER\SOFTWARE\Clients
HKEY_CURRENT_USER\SOFTWARE\CodeBlocks
HKEY_CURRENT_USER\SOFTWARE\Discord
HKEY_CURRENT_USER\SOFTWARE\Dropbox
HKEY_CURRENT_USER\SOFTWARE\DropboxUpdate
HKEY_CURRENT_USER\SOFTWARE\ej-technologies
HKEY_CURRENT_USER\SOFTWARE\Evernote
HKEY_CURRENT_USER\SOFTWARE\GNU

And I need to have a new file where the new lines contain only part of those strings, like:

7-Zip
AppDataLow
Chromium
Clients
...

how to do it in python?

CodePudding user response:

One approach would be to read the entire text file into a Python string. Then use split on each line to find the final path component.

with open('file.txt', 'r') as file:
    data = file.read()

lines = re.split(r'\r?\n', data)
output = [x.split("\\")[-1] for x in lines]

# write to file if desired
text = '\n'.join(output)
f_out = open('output.txt', 'w')
f_out.write(text)
f_out.close()

CodePudding user response:

Try this:

## read file content as string
with open("file.txt", "r") as file:
    string = file.read()
    
## convert each line to list
lines = string.split("\n")

## write only last part after "\" in each line
with open("new.txt", "w") as file:
    for line in lines:
        file.write(line.split("\\")[-1]   "\n")
  • Related