I have created a program in python that uses a .txt file as a database, so I save the user data there. The data is stored in the file as follows:
- Each line in the file represents a user
- Users are stored as:
User_ID,First Name,Last Name,Phone Number,Country
The problem arises when I try to delete a user that is in the last position of the file, because it leaves a blank line that breaks the function of listing the users in the program.
Example:
Suppose I have two users in the text file: image1
And now I delete the last user (00002): image2
So, there is a blank line, and when I add a new user, it looks like this: image3
Here is the code I use to delete users:
def delete_user(file, user_id):
with open(file, 'r ') as f:
users = f.readlines()
f.seek(0)
for user in users:
if user.split(',')[0] != user_id:
f.write(user)
f.truncate()
Code I use to add users:
def add_user(file, first_name, last_name, phone_number, country):
filesize = os.path.getsize(file)
with open(file, 'r ') as f:
if filesize == 0:
f.write(f'{"1".zfill(5)},{first_name},{last_name},{phone_number},'
f'{country}')
else:
last_line = f.readlines()[-1]
user_id = int(last_line.split(',')[0])
f.write(f'\n{str(user_id 1).zfill(5)},{first_name},{last_name},'
f'{phone_number},{country}')
Upon investigation, I realized that the problem occurs because there is a newline character (\n) left at the end of the last line, which should not be there. So, how could I solve this problem?
CodePudding user response:
A trailing newline shouldn't break your program. You seem to be using a newline as a line separator, but on Unix-like OSs, a newline is actually considered a line terminator, meaning there should be one at the end of every line.
However, you'll have a much easier time by using a standard data format. What you're using resembles CSV, so I recommend csv.DictReader
and csv.DictWriter
, which would also involve putting a column header in the file to label the fields. You might also consider using Pandas (e.g. pandas.read_csv()
and df.to_csv()
).