Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在csv文件的每一行中写入值?_Python_Csv - Fatal编程技术网

Python 如何在csv文件的每一行中写入值?

Python 如何在csv文件的每一行中写入值?,python,csv,Python,Csv,我使用循环为csv文件的每一行计算一个值,并希望将该值作为每一行中的新列写入 我打开文件: with open('hello.csv', 'r', encoding="latin-1") as csvfile: readCSV = csv.reader(csvfile, delimiter=',') list1 = list(readCSV) 然后循环行并计算新值: for j in list1: dt=j[1] dt2=dt+1 如何将每行“j”中的dt2作

我使用循环为csv文件的每一行计算一个值,并希望将该值作为每一行中的新列写入

我打开文件:

with open('hello.csv', 'r', encoding="latin-1") as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    list1 = list(readCSV)
然后循环行并计算新值:

for j in list1:
    dt=j[1]
    dt2=dt+1
如何将每行“j”中的dt2作为现有csv文件“hello.csv”中的新列写入

从评论中复制:

这只是一个简单的例子。我已将数据时间对象转换为正确的时区:

dtstr=j[1] #string 
hours, minutes = [int(t) for t in tstr.split(':')] 
dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S') + 
              timedelta(hours=hours+4, minutes=minutes)

使用python
csv
模块,在
outfile
中创建一个新列并写入行,新列表中添加了
new\u column\u值

with open('hello.csv', 'r', encoding="latin-1") as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    with open('helloout.csv', 'w', encoding="latin-1") as outfile:
        outCSV = csv.writer(outfile,delimiter=',')
        for line in readCSV:
            new_column_value = func(line[j]) # Your modification function j column number
            new_line = line + [new_column_value]
            outCSV.writerow(newline)

我只变成了一个csv文件helloout.csv,只有一行,这是hello.csv文件的最后一行,有了新的列。我想它会覆盖行,但我不知道为什么?

dt2
转换为日期字符串并将其追加:
j.append()
dt2在我的例子中是一个datetime.datetime对象。如何将其转换为日期字符串?当我使用它时,我变成了文件helloout.csv,只有一行,最后一行。。我认为它会覆盖行或类似的内容。。我向您展示我的代码:在这种情况下,请尝试附加模式。因为您反复打开和关闭文件。最好是像我在回答中所做的那样在外部for循环中使用open文件处理程序,或者将open('hello out.csv','a+',encoding=“latin-1”)更改为outfile:
 with open('hello.csv', 'r', encoding="latin-1") as csvfile:
          readCSV = csv.reader(csvfile, delimiter=',')
          list1 = list(readCSV)
          for j in list1:
              dtstr=j[1] #string
              hours, minutes = [int(t) for t in tstr.split(':')]
              dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S')         +timedelta(hours=hours+4, minutes=minutes)
              with open('hello out.csv', 'w', encoding="latin-1") as outfile:
                    outCSV = csv.writer(outfile,delimiter=',')
                    newline = j + [dt]
                    outCSV.writerow(newline)