Ad

Slice A Given Txtfile And Write Only Part Of It In A Newfile In Python

- 1 answer

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?

Ad

Answer

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")
Ad
source: stackoverflow.com
Ad