0
我目前正在處理CSV文件創建編輯並追加到CSV文件我遇到的問題是我試圖更新到現有的CSV文件,但這樣做時遇到了麻煩。在Python中更新CSV文件
當我運行代碼時我收到以下錯誤。
/usr/bin/python3.5 /home/usr/PycharmProjects/csv/csv_file.py
2016-11-12 00:04:03.975247
2016-11-11 23:59:17.591426
MOD TIME IS Different
Traceback (most recent call last):
File "/home/usr/PycharmProjects/csv/csv_file.py", line 157, in <module>
Direcotry_function(sys.argv)
File "/home/usr/PycharmProjects/csv/csv_file.py", line 133, in Direcotry_function
for row in reader:
File "/usr/lib/python3.5/csv.py", line 109, in __next__
self.fieldnames
File "/usr/lib/python3.5/csv.py", line 96, in fieldnames
self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
Process finished with exit code 1
下面是Python代碼,我似乎無法工作。
def function(dest):
global directory_path #call the Global Variable
directory_path = os.getcwd() # getting Current Directory
if len(dest) > 1:
directory_path = dest
for list in filepath_list:
Originalfiles = ''.join(list)#Convert to Str
drive, path = os.path.splitdrive(Originalfiles)#Get the Path
path, filename = os.path.split(path)#Split the path and filename
makedir = path + '/' + filename
Originalfiles_Timestamp = os.path.getmtime(Originalfiles)#Get the Timestamp of File in seconds
mTime = datetime.datetime.fromtimestamp(Originalfiles_Timestamp)#Get the Date time in Month Yearformat
print(mTime)
if os.path.exists(os.path.join(directory_path, filename[:]+".copy")):#Check if the FIle exists
file_csv = csv.DictReader(open('datetime.csv'))#open CSV FILE
for row in file_csv:#Loop over
if row['FileName'] == Originalfiles:
rowTime = datetime.datetime.strptime(row['ModificationDate'], "%Y-%m-%d %H:%M:%S.%f") #Convert row to DateTime
print(rowTime)
if rowTime == mTime: #Check if Time inside CSV equals mTime
print("DATE IS THE SAME")
exit(1)
else:#if not equaled
print("MOD TIME IS Different")
global CSV_FILENAME
temp_file = NamedTemporaryFile(delete=False)
with open(CSV_FILENAME, "rb") as f, temp_file:
reader = csv.DictReader(f)
fieldnames = ['FileName', 'ModificationDate'] # Create Dict Keys
writer = csv.DictWriter(f, fieldnames=fieldnames)
for row in reader:
print(row)
writer.writerow({"FileName": row['FileName'], "ModificationDate": mTime})
shutil(temp_file.name, CSV_FILENAME)
os.system('cp -rv ' + makedir + ' ' + directory_path + '/' + filename[:] + ".copy")
else:
with open('datetime.csv', 'a+') as f:
fieldnames = ['FileName', 'ModificationDate']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()#WRITE KEYS
writer.writerow({'FileName': Originalfiles, 'ModificationDate': mTime})#WRITE Values
else:
#If Copy File Does not Exists in the Folder do the Following:
os.system('cp -r ' + makedir + ' ' + directory_path + '/' + filename[:]+".copy")#Copy ther File to the Directory
with open('datetime.csv', 'a+') as csvfile:#Open CSV File
fieldnames = ['FileName', 'ModificationDate']#Create Dict Keys
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'FileName': Originalfiles, 'ModificationDate': mTime})#Write to The CSV File
編輯:
所以守則玩弄後:我這樣做其工作是在某一點之後,這個問題我面對它不讀取整個datetime.csv如果我恰克東西在一個文件中我得到這個 它不給我test1的在temp.csv內
文件名,時間modificationdate /家庭的/ usr /桌面/ test23,2016-11-12 11:22:07.410170 文件名,時間modificationdate /home/usr/Desktop/test23,2016-11-12 11:22:07.410170 文件名,時間modificationdate /家庭的/ usr /桌面/ test23,2016-11-12 11:22:07.410170
def Direcotry_function(directory_dest):
global directory_path #call the Global Variable
directory_path = os.getcwd() # getting Current Directory
if len(directory_dest) > 1:
directory_path = directory_dest
for list in filepath_list:
Originalfiles = ''.join(list)#Convert to Str
drive, path = os.path.splitdrive(Originalfiles)#Get the Path
path, filename = os.path.split(path)#Split the path and filename
makedir = path + '/' + filename
Originalfiles_Timestamp = os.path.getmtime(Originalfiles)#Get the Timestamp of File in seconds
mTime = datetime.datetime.fromtimestamp(Originalfiles_Timestamp)#Get the Date time in Month Yearformat
print(mTime)
print(filename)
if os.path.exists(os.path.join(directory_path, filename[:]+".copy")):#Check if the FIle exists
file_csv = csv.DictReader(open('datetime.csv'))#open CSV FILE
for row in file_csv:#Loop over
if row['FileName'] == Originalfiles:
rowTime = datetime.datetime.strptime(row['ModificationDate'], "%Y-%m-%d %H:%M:%S.%f") #Convert row to DateTime
if rowTime == mTime: #Check if Time inside CSV equals mTime
print("same")
else:
with open('datetime.csv', "r") as f:
reader = csv.DictReader(f)
fieldnames = ['FileName', 'ModificationDate'] # Create Dict Keys
for row in reader:
with open("temp.csv", 'w') as g:
writer = csv.DictWriter(g, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"FileName": Originalfiles, "ModificationDate": mTime})
#shutil.move("temp.csv", 'datetime.csv')
os.system('cp -rv ' + makedir + ' ' + directory_path + '/' + filename[:] + ".copy")
else:
#If Copy File Does not Exists in the Folder do the Following:
os.system('cp -r ' + makedir + ' ' + directory_path + '/' + filename[:]+".copy")#Copy ther File to the Directory
with open('datetime.csv', 'a') as csvfile:#Open CSV File
fieldnames = ['FileName', 'ModificationDate']#Create Dict Keys
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'FileName': Originalfiles, 'ModificationDate': mTime})#Write to The CSV File
當我使用 'R',我得到'管線135,在Direcotry_function writer.writeheader()' – Noa
如果我拿出裏邊反writeheader我正在以下,線136,在Direcotry_function writer.writerow( {「FileName」:Originalfiles,「ModificationDate」:mTime}) – Noa