Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

remove characters from a file with python

I have created a file and written content to it with this code:

# create file
file = open("myFile", "w")

# write contents to file
file.write("Hello World!")

Now I want to remove characters at specific positions i. e. the last one.

How do I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

After Your Code.

# read file
file = open("myFile", "r")
data = file.read() #--> Read the content inside the 'myFile.txt'
file.close()

# write to file except last word.
file = open("myFile", "w")
file.write(data[:-1])#--> Write the above data in the file again but except last letter
file.close()
# What does data[:-1] mean.
# example if data = "Hello World", then
# data[:-1] == "Hello Worl"
# clearly data[:-1] mean letter start from index 0 to -2(second last value of the string)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading