MCPcopy Index your code
hub / github.com/InstaPy/InstaPy / delete_line_from_file

Function delete_line_from_file

instapy/util.py:930–998  ·  view source on GitHub ↗

Remove user's record from the followed pool file after unfollowing

(filepath, userToDelete, logger)

Source from the content-addressed store, hash-verified

928
929
930def delete_line_from_file(filepath, userToDelete, logger):
931 """Remove user's record from the followed pool file after unfollowing"""
932 if not os.path.isfile(filepath):
933 # in case of there is no any followed pool file yet
934 return 0
935
936 try:
937 file_path_old = filepath + ".old"
938 file_path_Temp = filepath + ".temp"
939
940 with open(filepath, "r") as f:
941 lines = f.readlines()
942
943 with open(file_path_Temp, "w") as f:
944 for line in lines:
945 entries = line.split(" ~ ")
946 sz = len(entries)
947 if sz == 1:
948 user = entries[0][:-2]
949 elif sz == 2:
950 user = entries[1][:-2]
951 else:
952 user = entries[1]
953
954 if user == userToDelete:
955 slash_in_filepath = "/" if "/" in filepath else "\\"
956 filename = filepath.split(slash_in_filepath)[-1]
957 logger.info(
958 "\tRemoved '{}' from {} file".format(
959 line.split(",\n")[0], filename
960 )
961 )
962
963 else:
964 f.write(line)
965
966 # File leftovers that should not exist, but if so remove it
967 while os.path.isfile(file_path_old):
968 try:
969 os.remove(file_path_old)
970
971 except OSError as e:
972 logger.error(
973 "Can't remove file_path_old \n\t{}".format(str(e).encode("utf-8"))
974 )
975
976 # rename original file to _old
977 os.rename(filepath, file_path_old)
978
979 # rename new temp file to filepath
980 while os.path.isfile(file_path_Temp):
981 try:
982 os.rename(file_path_Temp, filepath)
983
984 except OSError as e:
985 logger.error(
986 "Can't rename file_path_Temp to filepath \n\t{}".format(
987 str(e).encode("utf-8")

Callers 4

unfollowFunction · 0.85
post_unfollow_cleanupFunction · 0.85
set_followback_in_poolFunction · 0.85

Calls 1

sleepFunction · 0.85

Tested by

no test coverage detected