So I'm fairly new to Python. After going through a few different tutorials and such I've decided to try and make a simple program, one of the things in it I need it to remove a line in a txt file. Here's the code I currently have:
name = raw_input("What name would you like to remove: ")
templist = open("oplist.txt").readlines()
templist_index = templist.index(name)
templist.remove(templist_index)
target = open("oplist.txt", "w")
target.write(templist)
target.close
However when templist is made it stores the data like "example1\n" which if the user only typed example it wouldn't work. Is there any simpler ways to this or fix? Thanks for the assistance.
use rstrip to remove the newlines chars and use with to open your files:
with open("oplist.txt") as f: # with opens and closes the file automtically
templist = [x.rstrip() for x in f] # strip new line char from every word
You could also concat a newline char to name:
templist_index = templist.index(name+"\n") # "foo" -> "foo\n"
The full code:
with open("oplist.txt") as f:
temp_list = [x.rstrip() for x in f]
name = raw_input("What name would you like to remove: ")
temp_list.remove(name) # just pass name no need for intermediate variable
with open("oplist.txt", "w") as target: # reopen with w to overwrite
for line in temp_list: # iterate over updated list
target.write("{}\n".format(line)) # we need to add back in the new line
# chars we stripped or all words will be on one line
Related
I am trying to create a contact info txt file with python
what_you_want = input("Do you want to add or remove (if add write add), (if remove write remove): ")
if what_you_want == "remove":
what_you_want_remove = input("What contact number you want to remove: ")
with open("All Contact.txt", "r") as f:
contact_info = f.readlines()
if what_you_want_remove in contact_info:
with open("All Contact.txt", "a") as f:
if what_you_want_remove in contact_info:
new_contact_info = contact_info.replace(what_you_want_remove, "")
f.write(new_contact_info)
I couldn't find a way to directly remove something from a txt file so I want to put it into a list and then write it back to txt file but when I try to use remove command it doesn't work.
I want to ask if there is a way to remove something from a text file directly.
You can read the file into a string or list, remove the substring, and write back to the file. For instance,
with open("file.txt", "w") as f:
string = f.readlines()
string = string.replace(substring, "")
f.write(string)
If substring does not exist in file.txt, the replace function will not perform any action. If you want the replacement to be case-insensitive, you could try lowering the entire buffer as well as the subtring via string = string.lower() and substring = substring.lower().
Use del to delete that entry.
Then overwrite the original file, making it one line shorter.
if what_you_want_remove in contact_info:
i = contact_info.index(what_you_want_remove)
del contact_info[i]
with open("All Contact.txt", "w") as fout:
fout.write("\n".join(contact_info)
fout.write("\n")
I have txt file which looks like:
New York,cinema,3,02/04/2022
But I've got error in list, even if this code works to another txt files without date, what's the problem?
def finished_objects():
file = open("finished_objects.txt", "r",encoding="UTF8")
lines = file.readlines()
L = [] # assign empty list with name 'L'
for line in lines:
L.append(line.replace("\n", "").split(","))
file.close()
for i in range(len(L)):
print(L[i][0], ":", L[i][1], ". Quantity:", L[i][2], ". Date: ", L[i][3])
return L
You can also use "with" for opening files like,
with open("finished_objects.txt", "r",encoding="UTF8") as file:
lines = file.readlines()
L = [] # assign empty list with name 'L'
for line in lines:
L.append(line.replace("\n", "").split(","))
# rest of your code
That way you don't have to manage the connection.
Works fine on my end. Might be that your file has one entry with less commas than others. You could do a simple if len(L) != 4 inside your last loop to make sure you won't get errors while running.
I'm currently making this program that was given to me by my school and it's to write your own name in ASCII text art but that was just copying and pasting. I am trying to make it so the user enters an input and there their name is output. My program currently works except it doesnt stay on one line.
My code:
name = input("What is your name: ")
splitname = list(name)
for i in range(len(splitname)):
f=open(splitname[i] + ".txt","r")
contents = f.read()
print(contents)
And this is what it outputs:
I would like to get it all onto one line if possible, how would I do so?
The solution is a bit more complicated because you have to print out line by line, but you already need all the contents of the 'letter' files.
The solution would be to read the first line of the first letter, then concatenate this string with the first line of the next letter and so on. Then do the same for the second line until you printed all lines.
I will not provide a complete solution, but I can help to fix your code. To start you have to only read one line of the letter file. You can do this with f.readline() instead of f.read() each consecutive call of this function will read the next line in this file, if the handle is still open.
To print the ASCII letters one next to the other, you have to split the letter into multiple lines and concatenate all the corresponding lines.
Assuming your ASCII text is made of 8 lines:
name = input("What is your name: ")
splitname = list(name)
# Put the right number of lines of the ASCII letter
letter_height = 8
# This will contain the new lines
# obtained concatenating the lines
# of the single letters
complete_lines = [""] * letter_height
for i in range(len(splitname)):
f = open(splitname[i] + ".txt","r")
contents = f.read()
# Split the letter in lines
lines = contents.splitlines()
# Concatenate the lines
for j in range(letter_height):
complete_lines[j] = complete_lines[j] + " " + lines[j]
# Print all the lines
for j in range(letter_height):
print(complete_lines[j])
if I have a file like:
Flower
Magnet
5001
100
0
and I have a list containing line number, which I have to change.
list =[2,3]
How can I do this using python and the output I expect is:
Flower
Most
Most
100
0
Code that I've tried:
f = open("your_file.txt","r")
line = f.readlines()[2]
print(line)
if line=="5001":
print "yes"
else:
print "no"
but it is not able to match.
i want to overwrite the file which i am reading
You may simply loop through the list of indices that you have to replace in your file (my original answer needlessly looped through all lines in the file):
with open('test.txt') as f:
data = f.read().splitlines()
replace = {1,2}
for i in replace:
data[i] = 'Most'
print('\n'.join(data))
Output:
Flower
Most
Most
100
0
To overwrite the file you have opened with the replacements, you may use the following:
with open('test.txt', 'r+') as f:
data = f.read().splitlines()
replace = {1,2}
for i in replace:
data[i] = 'Most'
f.seek(0)
f.write('\n'.join(data))
f.truncate()
The reason that you're having this problem is that when you take a line from a file opened in python, you also get the newline character (\n) at the end. To solve this, you could use the string.strip() function, which will automatically remove these characters.
Eg.
f = open("your_file.txt","r")
line = f.readlines()
lineToCheck = line[2].strip()
if(lineToCheck == "5001"):
print("yes")
else:
print("no")
Here's the code:
def predator_eat(file):
predator_prey = {}
file.read()
for line in file:
list = file.readline(line)
list = list.split(" ")
predator_prey[list[0]] = list[2]
print(predator_prey)
predator_eat(file)
The text file is three words per line with \n at the end of each line and I previously opened the file and stored the file name as the variable file
using file = open(filename.txt, r)
the print statement ends up being an empty dictionary so it isn't adding keys and values to the dictionary
please help
Your first call to .read() consumes the entire file contents, leaving nothing for the loop to iterate over. Remove it. And that .readline() call does nothing useful. Remove that too.
This should work:
def predator_eat(file):
predator_prey = {}
for line in file:
words = line.split(" ")
predator_prey[words[0]] = words[2]
print(predator_prey)
Cleaning up your code a little:
def predator_eat(f):
predator_prey = {}
for line in f:
rec = line.strip().split(" ")
predator_prey[rec[0]] = rec[2]
return predator_prey
with open(path) as f:
print predator_eat(f)
You basically re declaring python keywords, change file to fileToRead and list something else like totalList or something.