Why is it that if input 1, line 1 isn't deleted in a.txt?

x = open('a.txt','r')
l = []
q = 0
for line in x:
	l.append(str(line))
b = "".join(l)
print b
a = raw_input("Which line do you want to delete?: ")
l[int(a)] = ""
x.close()
x = open('a.txt','w')
x.write(b)
x.close()

Dani AI

Generated

Short answer: the file was being overwritten with the old contents and you were also relying on Python's zero-based indexing. As discovered, you built a string of the file before changing the list, then wrote that unchanged string back — so nothing appeared deleted. Also, assigning "" to a list element leaves a blank line; use del or pop to remove the element. was right to suspect "it isn't deleting".

A safer, clearer pattern:

  • show lines with numbers so the user can pick a 1-based line,
  • convert the choice to a 0-based index,
  • remove the element with pop (or del) instead of setting it to an empty string,
  • write the updated list back to disk using a context manager.

Example (Python 2 style; on Python 3 replace raw_input with input):

with open('a.txt', 'r') as f:
lines = f.readlines()

for i, ln in enumerate(lines, 1):
print("%d: %s" % (i, ln.rstrip('\n')))

try:
choice = int(raw_input("Which line to delete? ")) - 1
if choice < 0 or choice >= len(lines):
raise IndexError
lines.pop(choice)
except (ValueError, IndexError):
print("Invalid selection.")
else:
with open('a.txt', 'w') as f:
f.writelines(lines)

Extra tips: validate input, handle exceptions so you do not corrupt the file, and consider writing to a temporary file then atomically replacing the original for safety. See the Python docs for file I/O and list operations for more detail: File I/O and Lists.

Recommended Answers

All 2 Replies

Solved:

x = open('a.txt','r')
l = []
q = 0
for line in x:
	l.append(str(line))
b = "".join(l)
print b
a = raw_input("Which line do you want to delete?: ")
l[int(a)] = ""
b = "".join(l)
x.close()
x = open('a.txt','w')
x.write(b)
x.close()
Member Avatar for Member #361407

are you sure that it is deleting line a? from a quick glance it looks to me like it isn't

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.