Python 如何将字符串写入csv文件
我正在尝试创建一个带有一列文件路径的csv文件。我需要一个第二栏,里面填上 我想得到的结果如下:Python 如何将字符串写入csv文件,python,python-3.x,csv,numpy,Python,Python 3.x,Csv,Numpy,我正在尝试创建一个带有一列文件路径的csv文件。我需要一个第二栏,里面填上 我想得到的结果如下: ./1/a_1.csv, 1 ./1/a_2.csv, 1 ./1/a_3.csv, 1 我试过的代码是这样的 import numpy as np data=np.chararray((650,2), itemsize=20) for i in range(1, 650): data[0][0]="./1/a_" + str(i) + ".csv" np.savetxt("C:\\
./1/a_1.csv, 1
./1/a_2.csv, 1
./1/a_3.csv, 1
我试过的代码是这样的
import numpy as np
data=np.chararray((650,2), itemsize=20)
for i in range(1, 650):
data[0][0]="./1/a_" + str(i) + ".csv"
np.savetxt("C:\\a.csv", data, delimiter = ",")
然而,它似乎不起作用。你能帮忙吗?你不需要Numpy。做点像
with open('a.csv', 'w') as outf:
for i in range(650):
print('./1/a_%s.csv, 1' % (i + 1), file=outf)
你是黄金。在循环的每次迭代中,你只会对
数据[0][0]
进行写入。你需要改变你的循环来改变你在范围内循环时设置的数组位置。我个人喜欢将我的所有数据存储到一个数据框中,然后在最后,将其保存到一个csv文件中,而不是在每次迭代后写入
因此,我初始化了一个名为results
然后遍历您的范围,创建文件路径字符串。然后我用当前文件名字符串和第二列创建那一行。它被附加到结果数据框,然后移动到列表/范围中的下一项。继续该过程直到完成,然后将最终结果数据帧保存到文件
import pandas as pd
# initialize an empty dataframe
results = pd.DataFrame()
# iterates each element in the range list to form a row that is appended to the results dataframe
for i in range(1, 650):
file_path="./1/a_" + str(i) + ".csv"
temp_df = pd.DataFrame([[file_path, 1]], columns = ['file_path', 'col_2'])
results = results.append(temp_df.reset_index(drop = True))
# after iterating through all the elements, saves completed results dataframe to file
results.to_csv("a.csv", index=False))
如果你不关心文件是如何创建的(只要它能工作),那么就使用AKX的解决方案 如果你想用Numpy来做这件事,你需要弄清楚你的数据类型
np.savetxt
有一个默认的格式化程序,它无法理解您提供给它的数组
这就是我如何获得您想要的输出:
data = np.empty((650,2),dtype="S20") # empty array of the correct datatype
data[:,1] = '1' # set column 1 to '1' (as you noted)
for i in range(650):
data[i][0] = "./1/a_" + str(i) + ".csv" # put your filenames into first column
np.savetxt(r"C:\a.csv", data, delimiter = ",", fmt="%s") # save it using %s formatter
在csv文件中,分隔符为“;”非“,”
我会使用熊猫图书馆的数据帧。与chitown88的答案类似,但更简洁
import pandas as pd
# create a list with paths to files named from 1 to 256
file_paths = ["./1/a_{}.csv".format(i) for i in range(1,257)]
# add the list to a Pandas Dataframe, the column name can be omitted
df = pd.DataFrame(data=file_paths, columns=['Paths'])
# add a column of 1's to the DataFrame
df['1'] = 1
# write the DataFrame without the indices and column names to a csv file using a specific separation character
df.to_csv('C:\\a.csv', sep=',', index=False, header=False)
“似乎不起作用”是什么意思?会发生什么?你有错误吗?如果是,请也发布错误和回溯(如果有)。“TypeError:数组数据类型(“| S20”)和格式说明符(“%.18e,%.18e”)之间不匹配。”。我收到了这个错误,但是你发布的解决方案很有效,所以非常感谢你!你能提供一些关于该代码的功能/工作原理的信息吗?只有代码的答案往往不如有解释的答案那么有说服力。默认的分隔符是“
”,“
,因为这是最常用的分隔符,许多人认为“C”代表什么。但是没有标准,“;”
和许多其他字符一样好。打印的有趣用法。您的方法与将open('a.csv','w')作为myfile:myfile.write('./1/a_%s.csv,1')作为myfile的方法有什么区别吗?解释文件
参数。它表示文件
对象必须具有写入
方法。因此实际上它们是相同的(对于字符串输出)。print()
默认情况下也会添加换行符;我不想用额外的“\n”把原始代码弄乱`
import pandas as pd
# create a list with paths to files named from 1 to 256
file_paths = ["./1/a_{}.csv".format(i) for i in range(1,257)]
# add the list to a Pandas Dataframe, the column name can be omitted
df = pd.DataFrame(data=file_paths, columns=['Paths'])
# add a column of 1's to the DataFrame
df['1'] = 1
# write the DataFrame without the indices and column names to a csv file using a specific separation character
df.to_csv('C:\\a.csv', sep=',', index=False, header=False)