Add a character to a string - python

I am newbie with python and I have one problem with a small script I hope someone can give me a clue.
I have a file called "one.txt" which has the following 2 lines:
Hello
Goodbye
I want to add two characters ("/1") to the end of each line and write it in another file called result.txt:
result.txt
Hello1/
Goodbye1/
I tried the following:
x=open("one.txt","r")
y=open("result.txt","w")
for line in x:
line2= "/1" +line
y.write(line2)
and I get:
1/Hello
1/Goodbye
if I change line2 with:
line2= line + "/1"
I get:
Hello
/1Goodbye
/1
which is also not correct
any clues?

You forgot to strip the newline after reading the line and to add it back in before writing.

Here's yet another version, using context managers for the files (so you don't forget to close them later) - otherwise it's similar to the answer by #IgorPomaranskiy:
with open("one.txt") as x, open("result.txt", "w") as y:
for line in x:
y.write("{}\n".format(line.strip() + "/1"))

x = open("one.txt", "r")
y = open("result.txt", "w")
for line in x:
y.write("{}/1\n".format(line.strip())

When you read a line from a file, the string contains the newline character that indicated the end of the line. Your string isn't "Hello", it's "Hello\n". You need to remove that newline, create your output string, and add another newline when you write it back out.
for line in x:
line = line.rstrip('\n')
line2 = line + '/1\n'
y.write(line2)

Related

I'm trying to solve this Python exercise but I have no idea of how to do it: get first character of a line from a file + length of the line

I am learning Python on an app called SoloLearn, got to solve this exercise and I cannot see the solution or see the comments, I don't need to solve it to continue but I'd like to know how to do it.
Book Titles: You have been asked to make a special book categorization program, which assigns each book a special code based on its title.
The code is equal to the first letter of the book, followed by the number of characters in the title.
For example, for the book "Harry Potter", the code would be: H12, as it contains 12 characters (including the space).
You are provided a books.txt file, which includes the book titles, each one written on a separate line.
Read the title one by one and output the code for each book on a separate line.
For example, if the books.txt file contains:
Some book
Another book
Your program should output:
S9
A12
Recall the readlines() method, which returns a list containing the lines of the file.
Also, remember that all lines, except the last one, contain a \n at the end, which should not be included in the character count.
I tried:
file = open("books.txt","r")
for line in file:
for i in range(len(file.readlines())):
title = line[0]+str(len(line)-1)
print(titulo)
title = line[0]+str(len(line)-1)
print(title)
file.close
I also tried with range() and readlines() but I don't know how to solve it
This uses readlines():
with open('books.txt') as f: # Open file
for line in f.readlines(): # Iterate through lines
if line[-1] == '\n': # Check if there is '\n' at end of line
line = line[:-1] # If there is, ignore it
print(line[0], len(line), sep='') # Output first character and length
But I think splitlines() is easier, as it doesn't have the trailing '\n':
with open('books.txt') as f: # Open file
for line in f.read().splitlines(): # Iterate through lines
# No need to check for trailing '\n'
print(line[0], len(line), sep='') # Output first character and length
You can use "with" to handle file oppening and closing.
Use rstrip to get rid of '\n'.
with open('books.txt') as f:
lines = file.readlines()
for line in lines:
print(line[0] + str(len(line.rstrip())))
This is the same:
file = open('books.txt')
lines = file.readlines()
for line in lines:
print(line[0] + str(len(line.rstrip())))
file.close()

change text in text file in particular manner

I have a text file and there are some lines called
moves={123:abc:567:mno}
No I want to convert it in the form
moves={123:abc, 567:mno}
i.e. i want to replace : with , when ':' is after a string and behind a number i.e i want to make it like in a python dictionary format i know how i can change a particular line in the text file like
with open("images/filename.txt", 'r+', encoding='Latin1') as fp:
# read an store all lines into list
lines = fp.readlines()
# move file pointer to the beginning of a file
fp.seek(0)
# truncate the file
fp.truncate()
for line in lines:
if line.startswith('moves='):
do something()
fp.writelines(lines)
I am not being able to figure out how should i replace the line and make it in my desired why. Please don't delete or close the question tell me how i should edit the questionin the comments so i can change it instead.
Thanks in advance
If you have a line in your file (as a string) and it's exactly in that format then you can split the string on the colon separators then re-join with a comma in the appropriate place. For example:
s = 'moves={123:abc:567:mno}'
t = s.split(':')
print(':'.join(t[:2])+','+':'.join(t[2:]))
Output:
moves={123:abc,567:mno}
s = 'moves={123:abc:567:mno}'
t = s.split(':')
print(t[2:5])
# print(':'.join(t[:2])+','+':'.join(t[2:]))
output = ''
for i in range(int(len(t)/2)):
output += ':'.join(t[i*2:i*2 + 2]) + ', '
output = output.removesuffix(', ')
print(output)
Thanks #Lancelot du Lac to help me improvising your answer I have got the answer to my question

Appending string to a line read from file places appended string on next line

I have a .txt file like the following:
abc
def
ghi
Now, I want to add some string behind each row directly. However, my output is:
abc
---testdef
---testghi---test
My code is as follows:
file_read = open("test.txt", "r")
lines = file_read.readlines()
file_read.close()
new_file = open("res.txt", "w")
for line in lines:
new_file.write(line + "---test") # I tried to add "\r" in the middle of them, but this didn't work.
new_file.close()
You need to strip the new line using .rstrip():
for line in lines:
new_file.write(f"{line.rstrip()}---test\n")
Then, res.txt contains:
abc---test
def---test
ghi---test
What I understood is, you want to add a string behind a string, for example "abcd" should be changed into "---testabcd".
So the mistake you made is in new_file.write(line + "---test"), if you want add string1 before a string2, then you have to specify string1 first then string2.
So change it tonew_file.write("---test" + line)
Tip: Instead of using '+' operator, use f strings or .format.
f"---test{line}" this is f string.
"Hello {friends}".format(friends="myname")
For use of '\r':
Whenever you will use this special escape character \r, the rest of the content after the \r will come at the front of your line and will keep replacing your characters one by one until it takes all the contents left after the \r in that string.
print('Python is fun')
Output: Python is fun
Now see what happens if I use a carriage return here
print('Python is fun\r123456')
Output: 123456 is fun
So basically, it just replaces indexes of string to character after \r.

python string find and replace in text file

I'm reading a file and replacing a text string. I'm doing this for a few different strings, I know this isn't the most effeciant code I'm just trying to get it working. Here's what I have:
for line in fileinput.input(new_config, inplace=1):
print line.replace("http://domain.com", self.site_address)
print line.replace("dbname", self.db_name)
print line.replace("root", self.db_user)
print line.replace("password", self.db_pass)
print line.replace("smvc_", self.prefix
this works but it also writes every line in the file 5 times and only replaces the string on the first attempt on not on the new lines it creates (doesn't matter if it matches the string or not)
You just need to treat it as one string and apply all replacements to it.
for line in fileinput.input(new_config, inplace=1):
line = line.replace("http://domain.com", self.site_address)
line = line.replace("dbname", self.db_name)
line = line.replace("root", self.db_user)
line = line.replace("password", self.db_pass)
line = line.replace("smvc_", self.prefix)
print line
If it doesn't find any of those targets it will just not make any change to the line string so it will just replace what it DOES find.
for line in fileinput.input(new_config, inplace=1):
print line.replace(
"http://domain.com", self.site_address).replace(
"dbname", self.db_name).replace(
"root", self.db_user).replace(
"password", self.db_pass).replace("smvc_", self.prefix)
Done by copying and pasting what you wrote and using only the delete key and re-indenting. No characters added except the last closing paren.
Alternatively, this format may be clearer. It uses the backslash character to split the one line in a neater way, for better readability:
print line.replace("http://domain.com", self.site_address) \
.replace("dbname", self.db_name) \
.replace("root", self.db_user) \
.replace("password", self.db_pass) \
.replace("smvc_", self.prefix)
You can read a file line by line.
And at every line look for the word you would like to replace.
For example:
line1 = 'Hello World There'
def Dummy():
lineA = line1.replace('H', 'A')
lineB = lineA.replace('e', 'o')
print(lineB)
Dummy()
Then wirte lineB to a file.

Read/Write text file

I am trying to change a some lines in a text file without affecting the other lines. This is what's inside the text file called "text.txt"
this is a test1|number1
this is a test2|number2
this is a test3|number2
this is a test4|number3
this is a test5|number3
this is a test6|number4
this is a test7|number5
this is a test8|number5
this is a test9|number5
this is a test10|number5
My objective is to change the line 4 and line 5 but keep the rest same.
mylist1=[]
for lines in open('test','r'):
a=lines.split('|')
b=a[1].strip()
if b== 'number3':
mylist1.append('{}|{} \n'.format('this is replacement','number7'))
else:
mylist1.append('{}|{} \n'.format(a[0],a[1].strip()))
myfile=open('test','w')
myfile.writelines(mylist1)
Even though the code works, I am wondering if there is any better and efficient way to do it? Is it possible to read the file just by line number?
There is not much you can improve. But you have to write all lines to a new file, either changed or unchanged. Minor improvements would be:
using the with statement;
avoiding storing lines in a list;
writing lines without formatting in the else clause (if applicable).
Applying all of the above:
import shutil
with open('test') as old, open('newtest', 'w') as new:
for line in old:
if line.rsplit('|', 1)[-1].strip() == 'number3':
new.write('this is replacement|number7\n')
else:
new.write(line)
shutil.move('newtest', 'test')
import fileinput
for lines in fileinput.input('test', inplace=True):
# inplace=True redirects stdout to a temp file which will
# be renamed to the original when we reach the end of the file. this
# is more efficient because it doesn't save the whole file into memeory
a = lines.split('|')
b = a[1].strip()
if b == 'number3':
print '{}|{} '.format('this is replacement', 'number7')
else:
print '{}|{} '.format(a[0], a[1].strip())
No. Files are byte-oriented, not line-oriented, and changing the length of a line will not advance the following bytes.
try this solution
with open('test', inplace=True) as text_file:
for line in text_file:
if line.rsplit('|', 1)[-1].strip() == 'number3':
print '{}|{} \n'.format('this is replacement', 'number7')
else:
print line
It's not wholly clear whether your intent is to identify the lines to be replaced by their value, or by their line number.
If the former is your intent,
you can get a list of lines like this:
with open('test','r') as f:
oldlines = f.read().splitlines()
If there's a danger of trailing whitespace, you could also:
Then you can process them like this:
newlines = [ line if not line.strip().endswith('|number3') else 'this is replacement|number7' for line in oldlines]
Open the destination file (I'm assuming you want to overwrite the original, here), and write all the lines:
with open('test','w') as f:
f.write("\n".join(newlines))
This is a general pattern that's useful for any kind of simple line-filtering.
If you meant to identify the lines by number, you could just alter the 'newlines' line:
newlines = [ line if i not in (3, 4) else 'this is replacement|number7' for i, line in enumerate(oldlines)]

Categories