如何使用 python 写入 csv 文件
how to write csv file using python
我有一个 python 脚本,它从 csv 文件读取并将值存储在列表中,
其中值为 Dates row[0]、float row[10]、Boolean row[11].
该脚本在阅读部分工作得很好,但是当我尝试将选定的值写入第二个 CSV 文件时,系统会创建一个 仅包含 headers 的文件,并且系统崩溃并显示此错误:
line 62, in
fwriter.writerow("{}:{}:{}".format(row[0],row[10],row[11]))
builtins.IndexError: string index out of range
代码哪里出错了?
代码:
import csv
mydelimeter = csv.excel()
mydelimeter.delimiter=";"
myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv")
# read the first line in the opened file ==> Header
myfile.readline()
myreader=csv.reader(myfile,mydelimeter)
result=[]
'''
create a variable that handle values of the 3 fields
==> Date - fastest5secwindspeed - fog
and display the result where
fog ==> Yes and highest speed more than 10.
'''
for index ,row in enumerate(myreader):
try:
'''
check if the values in the fog colums is == Yes
if ok
check if the column of the "fastwindspeed"
is empty ==> raise Exception
check if the value in column of the "fastwindspeed"
is < 10.0 ==> raise Exception
else print the results
'''
if row[11] =="Yes":
if row[10] in (None, ""):
raise Exception( "this Record has empty value" )
if float(row[10]) < 10.0:
raise Exception( 'the wind speed is below 10 mph in ' + row[0] )
print(row[0],row[10],row[11])
'''
append the result into a list
in order to use it in the writing of the new csv file
'''
result.append(row[0])
result.append(row[10])
result.append(row[11])
except Exception as e:
print("{}:{}".format(index ,e))
myfile.close()
'''
create a second csv file and append the selected result from the 1st csv file
'''
with open("C:/Users/test/Documents/Python_Projects/rduSpeedFog.csv", "w") as f:
headers = ["Date","WindSpeed","Fog"]
fwriter=csv.writer(f,mydelimeter)
fwriter.writerow(headers)
for row in result:
fwriter.writerow("{}:{}:{}".format(row[0],row[10],row[11]))
print("Writing Complete")
f.close()
使用@Bamar 的回答后
我得到了这个结果
csv file as result
在第一个循环中,每个字符串都放入 result
列表的单独元素中,因此它不是行列表。
您应该将该循环更改为使用:
result.append([row[0], row[10], row[11]])
将这些字段附加为每一行的列表。
在第二个循环中你使用了 csv.writer
,所以它会添加分隔符,你不应该使用 format
。随便写:
fwriter.writerow(row)
并且如果您希望输出文件中的字段分隔符为 :
,请使用:
fwriter=csv.writer(f,":")
writerow
将序列作为参数,但您传递的是字符串。尝试将您的值作为列表传递。
我有一个 python 脚本,它从 csv 文件读取并将值存储在列表中, 其中值为 Dates row[0]、float row[10]、Boolean row[11].
该脚本在阅读部分工作得很好,但是当我尝试将选定的值写入第二个 CSV 文件时,系统会创建一个 仅包含 headers 的文件,并且系统崩溃并显示此错误:
line 62, in
fwriter.writerow("{}:{}:{}".format(row[0],row[10],row[11]))builtins.IndexError: string index out of range
代码哪里出错了?
代码:
import csv
mydelimeter = csv.excel()
mydelimeter.delimiter=";"
myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv")
# read the first line in the opened file ==> Header
myfile.readline()
myreader=csv.reader(myfile,mydelimeter)
result=[]
'''
create a variable that handle values of the 3 fields
==> Date - fastest5secwindspeed - fog
and display the result where
fog ==> Yes and highest speed more than 10.
'''
for index ,row in enumerate(myreader):
try:
'''
check if the values in the fog colums is == Yes
if ok
check if the column of the "fastwindspeed"
is empty ==> raise Exception
check if the value in column of the "fastwindspeed"
is < 10.0 ==> raise Exception
else print the results
'''
if row[11] =="Yes":
if row[10] in (None, ""):
raise Exception( "this Record has empty value" )
if float(row[10]) < 10.0:
raise Exception( 'the wind speed is below 10 mph in ' + row[0] )
print(row[0],row[10],row[11])
'''
append the result into a list
in order to use it in the writing of the new csv file
'''
result.append(row[0])
result.append(row[10])
result.append(row[11])
except Exception as e:
print("{}:{}".format(index ,e))
myfile.close()
'''
create a second csv file and append the selected result from the 1st csv file
'''
with open("C:/Users/test/Documents/Python_Projects/rduSpeedFog.csv", "w") as f:
headers = ["Date","WindSpeed","Fog"]
fwriter=csv.writer(f,mydelimeter)
fwriter.writerow(headers)
for row in result:
fwriter.writerow("{}:{}:{}".format(row[0],row[10],row[11]))
print("Writing Complete")
f.close()
使用@Bamar 的回答后
我得到了这个结果
csv file as result
在第一个循环中,每个字符串都放入 result
列表的单独元素中,因此它不是行列表。
您应该将该循环更改为使用:
result.append([row[0], row[10], row[11]])
将这些字段附加为每一行的列表。
在第二个循环中你使用了 csv.writer
,所以它会添加分隔符,你不应该使用 format
。随便写:
fwriter.writerow(row)
并且如果您希望输出文件中的字段分隔符为 :
,请使用:
fwriter=csv.writer(f,":")
writerow
将序列作为参数,但您传递的是字符串。尝试将您的值作为列表传递。