如何在Python中写入.txt文件?
我想将以下信息写入.txt文件:如何在Python中写入.txt文件?,python,Python,我想将以下信息写入.txt文件: D = 68601 w = 1500 NNZ = 205806000 docword = [[ 0 170 4] [ 0 1856 4] [ 0 838 3] ... [68601 1982 0] [68601 1981 0] [68601 0
D = 68601
w = 1500
NNZ = 205806000
docword = [[ 0 170 4]
[ 0 1856 4]
[ 0 838 3]
...
[68601 1982 0]
[68601 1981 0]
[68601 0 0]]
这是最终的.txt文件的外观--替换数字:
D
W
NNZ
docID wordID count
docID wordID count
docID wordID count
docID wordID count
...
docID wordID count
docID wordID count
docID wordID count
我试过这个:
datafile_path = "/path/to/docword.txt"
with open(datafile_path, 'w+') as datafile_id:
np.savetxt(datafile_id, data, fmt=['%d','%d','%d'], newline="\n")
还有:
with open('/path/to/docword.txt', 'ab') as outfile:
for data_slice in data:
np.savetxt(outfile, data_slice, fmt=['%d','%d','%d'])
它会花很长时间,而且不会做我想做的事,而且把它作为泡菜保存也不是我想要的。我希望能够打开文本文件,并且能够在其中看到相同的格式,一列三行,然后是三列三行。这是将数据写入文件的示例代码,这符合您的期望吗
D = 68601
w = 1500
NNZ = 205806000
docword = [[1, 2, 3], [4, 5, 6]]
text_file = open("Output.txt", "w")
text_file.write(str(D) + '\n')
text_file.write(str(w) + '\n')
text_file.write(str(NNZ) + '\n')
for row in docword:
for el in row:
text_file.write(str(el) + '\t')
text_file.write('\n')
text_file.close()
输出文件内容:
68601
1500
205806000
1 2 3
4 5 6
如果您试图使用
numpy.savetxt
只需传递一个文件路径,无需打开文件。
查看函数末尾的示例。
您要执行以下操作:
datafile_path = "/path/to/docword.txt"
np.savetxt(datafile_path, data, fmt='%d %d %d', newline="\n")
一个非常简单的方法是使用for循环。尽管numpy必须有更好的解决方案
import numpy as np
mat = np.arange(9).reshape(3,3)
n= mat.shape[0]
file = open("file.txt", "w")
for i in range(0, n):
line = mat[i:i+1]
file.write(str(line).strip("[").strip("]")+"\n")
file.close()
输出:
0 1 2
3 4 5
6 7 8
…那么实际生成的是什么?可能不是的副本,但肯定会检查出来。我想
fmt='%d%d'%d'
不是fmt=['%d','%d','%d']
谢谢。这个做了我想做的。