So, I have textfile with multiple lines:
orange
melon
applez
more fruits
abcdefg
And I have a list of strings that I want to check:
names = ["apple", "banana"]
Now I want to go through all the lines in the file, and I want to insert the missing strings from the names list, if they are not present. If they are present, then they should not be inserted.
Generally this should not be to difficult but taking care of all the newlines and such is pretty finicky. This is my attempt:
if not os.path.isfile(fpath):
raise FileNotFoundError('Could not load username file', fpath)
with open(fpath, 'r+') as f:
lines = [line.rstrip('\n') for line in f]
if not "banana" in lines:
lines.insert(0, 'banana')
if not "apple" in lines:
lines.insert(0, 'apple')
f.writelines(lines)
print("done")
The problem is, my values are not inserted in new lines but are appended. Also I feel like my solution is generally a bit clunky. Is there a better way to do this that automatically inserts the missing strings and takes care of all the newlines and such?
file_name = r'<file-path>' # full path of file
names = ["apple", "banana"] # user list of word
with open(file_name, 'r+') as f: # opening file as object will automatically handle all the conditions
x = f.readlines() # reading all the lines in a list, no worry about '\n'
# checking if the user word is present in the file or not
for name in names:
if name not in x: # if word not in file then write the word to the file
f.write('\n'+name )
You need to seek
to the first position in the file and use join to write each word into a new line, to overwrite its contents:
names = ["apple", "banana"]
with open(fpath, 'r+') as f:
lines = [line.rstrip('\n') for line in f]
for name in names:
if name not in lines:
# inserts on top, elsewise use lines.append(name) to append at the end of the file.
lines.insert(0, name)
f.seek(0) # move to first position in the file, to overwrite !
f.write('\n'.join(lines))
print("done")
First get a list of all the usernames in your file by using readlines()
and then use list comprehension to identify the missing usernames from your names
list. Create a new list and write that one to your file.
names = ["apple", "banana"]
new_list = List()
with open(fpath, 'r+') as f:
usernames = f.readlines()
res = [user for user in usernames if user not in names]
new_list = usernames + res
with open(fpath, 'r+') as f:
for item in new_list:
f.write("%s\n" % item)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.