出于某种原因,我用于检查修改后的文件的for循环两次插入相同的文件数据。我希望将文件数据一次插入到csv文件中。我正在使用熊猫将数据插入到csv文件中。如何解决此错误?
问题代码:
try:
PARENT_DIR = os.path.abspath('.')
assert os.path.basename(PARENT_DIR) == 'Projects_Website'
except AssertionError:
in_dir = False
while not in_dir:
os.chdir('..')
PARENT_DIR = os.path.abspath('.')
try:
assert os.path.basename(PARENT_DIR) == 'Projects_Website'
in_dir = True
break
except AssertionError:
continue
_history = ModHistory.history(os.path.abspath('./src/mod_history'))
os.chdir('../..')
PARENT_DIR = os.path.abspath('.')
for file in os.listdir(PARENT_DIR):
if file in MOD_FILES:
continue
else:
modTime = os.path.getmtime(file)
current = datetime.datetime.fromtimestamp(modTime).strftime('%Y-%d-%m %H:%M:%S')
history = _history
for file_name, timestamp in history.items():
if current == timestamp and file == file_name:
continue
else:
if current != timestamp and file == file_name:
MOD_FILES.append(file)
# Code for updating csv file here
elif file != file_name:
if file in FOLDERS:
continue
else:
history_manager = ModHistory(file, current)
history_manager.insert_history()
os.chdir('../..')
ModHistory:__init__
和insert_history()源:
__init__
:
def __init__(self, filename, timestamp):
current_path = os.path.abspath('.')
try:
assert os.path.basename(current_path) == 'mod_history'
except AssertionError:
if os.path.basename(current_path) == 'Projects_Website':
os.chdir('./src/mod_history')
elif os.path.basename(current_path) == 'src':
os.chdir('./mod_history')
del current_path
self.file = filename
self.timestamp = timestamp
insert_history():
def insert_history(self):
"""
Inserts file history data to csv file
"""
print(self.file)
print(self.timestamp)
df = pd.DataFrame({"filename": [self.file], "timestamp": [self.timestamp]}, dtype='category')
df.to_csv("modifications.csv", encoding="utf-8", mode='a', header=False)
Csv文件:
0,__init__.py,2020-10-26 19:01:10
0,_mod_history.py,2020-31-10 09:58:00
0,modifications.csv,2020-31-10 10:13:16
0,.gitignore,2020-24-10 11:23:50
0,README.md,2020-22-10 17:38:07
0,README.md,2020-22-10 17:38:07
0,requirements.txt,2020-31-10 10:34:37
0,requirements.txt,2020-31-10 10:34:37