Say I have a file with these contents:
username1:password1:dd/mm/yy
username2:password2:dd/mm/yy
username3:password3:dd/mm/yy
How can I remove the last (9) characters from each line to leave only the username and password using Python?
CodePudding user response:
Open the file up using open("file.txt", "r")
, read it into a string, loop over each individual line using .splitlines()
, then remove the last 9 characters using the index string[:-9]
.
>>> string = "username3:password3:dd/mm/yy"
>>> string[:-9]
'username3:password3'
CodePudding user response:
Open your file with open("fileName.ext") method and then iterate each line. on each line you can perform the slicing function [:]
eachLineData = 'username1:password1:dd/mm/yy'
expectedResult = eachLineData[:-9]
print(expectedResult)
Full Code Example:
# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
for line in Lines:
expectedResult = line[:-9]
print(expectedResult)
CodePudding user response:
Here's a solution. The same filename
is used when writing the result, so the original file will be overwritten (just use another filename
for this if that's not what you want).
# Read lines into list
filename = 'your_file_name'
with open(filename, 'r') as f:
lines = f.readlines()
# Remove last n characters.
# Each line has an additional '\n' at the end,
# so we have to remove that one as well,
# then tack it back on.
n = 9
lines = [line[:-(n 1)] '\n' for line in lines]
# Write modified lines back out
with open(filename, 'w') as f:
f.writelines(lines)
Once could get by with only opening the file once, but I think it's nice to have a separate reading ('r'
) and writing ('w'
) stage.
CodePudding user response:
Most safe..
- Your input file (file.txt)
username1:password1:dd/mm/yy
username2:password2:dd/mm/yy
username3:password3:dd/mm/yy
The magic code
with open("file.txt","r ") as f:
lines=[line[0:line.rindex(":")] "\n" for line in f.readlines()]
f.seek(0)
f.truncate()
f.writelines(lines)
The Output
username1:password1
username2:password2
username3:password3
CodePudding user response:
Regular expressions are your friends: A regular expression is a sequence of characters that looks for a specific search pattern. This code should work. Changing the 9 will change the amount of characters removed.
import re
line="username1:password1:dd/mm/yy"
print re.sub('.{0,9}\Z', '', line)
This concept extends to reading in a file just add a for loop