Im trying to replace a cetain element in a txt file.
let say that if i find the name in telephonelist.txt, i want i to change the number to this person with the input value of newNumber.
let's say that name = Jens, then i want it to return 99776612 that is the tlf number to Jens, and then the input of 'newNumber' will replace this number. i am new to python.
def change_number():
while True:
try:
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
datafile = open('telephonelist.txt')
if name in open('telephonelist.txt').read():
for line in datafile:
if line.strip().startswith(name):
line = line.replace(name,newNumber)
print('I found', name)
quit()
else:
print('I could not find',name+',','please try again!\n')
continue
except ValueError:
print('nn')
change_number()
This i telephonelist.txt
Kari 98654321
Liv 99776655
Ola 99112233
Anne 98554455
Jens 99776612
Per 97888776
Else 99455443
Jon 98122134
Dag 99655732
Siv 98787896
Load content, modify it, seek to beginning of the file, write the modified content again and then truncate the rest.
def change_number():
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
with open('telephonelist.txt', 'r+') as file:
data = file.read().splitlines()
data = [line if not line.split()[0] == name else f"{name} {newNumber}" for line in data]
file.seek(0)
file.write("\n".join(data))
file.truncate()
change_number()
Related
So I've written a simple program that allows user to enter a line they would like to edit and text they would like to put into that line
def edit_line(file):
a_file = open(file, 'r')
list_of_lines = a_file.readlines()
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
a_file = open(file, 'w')
a_file.writelines(list_of_lines)
a_file.close()
edit_line('sample.txt')
When I run the program it works fine. However, It asks the user to input the text first and the line number second.
What is the reason for this and how can I fix it?
If you want to fix the problem, just split the one line into two:
Instead of:
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
Do:
index = int(input('What line would you like to edit?: ')) - 1
list_of_lines[index] = input('Write your text here: ') + '\n'
And as the answer #Guy linked explains, when you are doing an assignment line of code, the right hand (value of the variable) is run before the left side.
Validation is everything! What would happen if the user's input for the line number wasn't within the range of lines read from the file?
Here's a more robust approach:
def edit_line(filename):
with open(filename, 'r+') as file:
lines = file.readlines()
while True:
try:
lineno = int(input('What line would you like to edit: '))
if 0 <= lineno < len(lines):
lines[lineno] = input('Write your text here: ') + '\n'
file.seek(0)
file.writelines(lines)
file.truncate()
break
else:
raise ValueError('Line number out of range')
except ValueError as e:
print(e)
edit_line('edit.txt')
I'm facing a problem where I can't finish my code.
There is a problem where upon running this code it comes up as an IndexError.
name = str(input("Please input the books name that you would like to borrow: ")
file = open("books.txt", "r")
file_contents = []
for line in file:
stripped_line = line.strip()
line_list = stripped_line.split()
file_contents.append(line_list)
file.close()
i = 0
for name in range(len(file_contents)):
i = i +1
if name == file_contents[i]:
table_3= [["Borrow Book","1"],
["Cancel Borrowing","2"]]
headers_3 = ["Details", "No."]
print(tabulate(table_3, headers_3, tablefmt = "grid"))
num = int(input("Please input 1 for confirmation of booking and 2 for canceling the booking: "))
file_contents[i] = changed_name
changed_name = str(changed_name)
if name == file_contents[i]:
IndexError: list index out of range
Example Of The File:
(books.txt)
Exile
Dancing In The Moonlight
Here is your complete solution . I hope it would help You
from tabulate import tabulate
name = str(input("Please input the books name that you would like to borrow: "))
file = open("books.txt", "r")
file_contents = [] #available books
for line in file:
line=line.strip()
file_contents.append(line)
file.close()
print("file content: ",file_contents)
i = 0
if name in file_contents:
table_3= [["Borrow Book","1"],["Cancel Borrowing","2"]]
headers_3 = ["Details", "No."]
print(tabulate(table_3, headers_3, tablefmt = "grid"))
num = int(input("Please input 1 for confirmation of booking and 2 for canceling the booking: "))
if(num==1):
try:
#user wants to withdraw that books so we've to remove that book from our available list of books
file_contents.remove(name)
#now we remove that book name from our available books.txt file
file=open("books.txt","w")
str1=" "
str1.join(file_contents)
file.write(str1)
print("Happy to serve you :-) visit again for more good books")
except Exception as e:
print("There is an error ",e)
else:
print("visit again for more good books")
You're missing with range keyword
Try this
for name in range(len(file_contents)):
#your work
I think you meant to iterate through the file_contents:
# code above elided
file.close()
for line in file_contents:
if name == line:
# following code elided
As the error says, an int cannot be iterable. How can you loop through 4?
The solution? Create a range of numbers:
for name in range(len(file_names)):
It would help if you posted the IndexError that you are getting.
And an example of the file you are opening?
What i think i could discover, is that you are using variable i als iterator, but i cannot find it in your loop.
def write_csv_file(filename):
with open(filename, "w") as csv_file:
file_name = csv_file
write = input("please enter the number of times you would like to enter "
"a text into then file onto a different line: ")
write = int(write)
for write in range(write):
x = input("please enter what you would like to add: ")
file_name.write(x)
exit()
xxx = input("please enter the name of the file you would like to print into: ")
print(write_csv_file(xxx))
Just add a line break to the write method;
file_name.write(f'{x}\n')
The \n part denotes a line break/new line.
def write_csv_file(filename):
with open(filename, "w") as csv_file:
file_name = csv_file
write = input("please enter the number of times you would like to enter "
"a text into then file onto a different line: ")
write = int(write)
for write in range(write):
x = input("please enter what you would like to add: ")
file_name.write(x)
file_name.write('\n')
exit()
xxx = input("please enter the name of the file you would like to print into: ")
print(write_csv_file(xxx))
add file_name.write('\n') this after write text.
\n denotes new line or line break.
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False
You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()
Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)
To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?
Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()
First, I have my txt file data here as:
51
2
2
49
15
2
1
14
I would like to convert them into a list to do further calculation, however I couldn't do it and I try to print it one by one by using for loop. Then the error message "Attributes error" kept showing up.
def main():
file = str(input("Please enter the full name of the desired file(with extension) at the prompt below: \n"))
print (get_value(file))
def get_value(file):
file_open = open(file,"r")
print (file_open.read())
a = len(file)
print ("Length =",a)
for line in range file_open:
print (line)
main()
def main():
file = str(input("Please enter the full name of the desired file(with extension) at the prompt below: \n"))
print (get_value(file))
def get_value(file):
file_open = open(file,"r")
lsLines = file_open.readlines()
lsLines = [int(x) for x in lsLines if len(x.strip()) > 0]
file_open.close()
return lsLines
main()
EDIT: wrong language.
with open("file.txt") as f:
ints = [int(line) in f.readlines()]