在Python中更新CSV文件

时间:2016-11-12 00:22:37

标签: python python-3.x csv

我目前正在处理CSV文件创建编辑并附加到CSV文件我遇到的问题是我正在尝试更新到现有的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如果我在一个文件中查找某些东西我得到这个 它没有在temp.csv中给我test1

文件名,时间modificationdate / home / usr / Desktop / test23,2016-11-12 11:22:07.410170 文件名,时间modificationdate / home / usr / Desktop / test23,2016-11-12 11:22:07.410170 文件名,时间modificationdate / home / usr / Desktop / 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

1 个答案:

答案 0 :(得分:0)

jQuery("#menu-main-menu .menu-item-has-children .sub-menu").hover( function() { jQuery("#menu-main-menu .menu-item-has-children a").addClass("main-menu-orange"); }, function() { jQuery("#menu-main-menu .menu-item-has-children a").removeClass("main-menu-orange"); } ); 模式只应用于二进制文件。对于文本文件,只需使用rb