所以我有一個要寫入檔案的字串。我 100% 確定字串沒有尾隨\n或換行符或類似的東西。但是,當我嘗試將它寫入檔案時,它會在檔案中添加一個新行,我不明白為什么。我需要在檔案的最后一行沒有自動添加\n. 你知道我該怎么做嗎?
書面檔案樣本: 
撰寫代碼(矩陣總是有 9 行 9 列):
output = ""
index = 0
for each_line in structure_matrix:
for each_tile in each_line:
output = str(each_tile)
index = 1
if index % 3 == 0 and index != 9:
output = "\n"
index = 0
file_to_write_in_predictions.write(output)
謝謝!
uj5u.com熱心網友回復:
所以我會怎么做。我將創建一個由您在使用資料時創建的行組成的新串列,然后在“with”陳述句中創建一個邏輯,將串列中的每個專案寫入一個 txt 檔案,除非它是最后一個,否則它會添加一個新行到它。我對以下資料進行了測驗,它似乎有效
some_data_c = [1, 2, 3, 4, 5, 6, 7, 8, 9]
some_data_r = [1, 2, 3, 4, 5, 6, 7, 8, 9]
output = ""
new_row = []
for c in some_data_c:
for r in some_data_r:
output = str(r)
new_row.append(output)
output = ""
print(new_row)
with open("test.txt", "w") as f:
for i in range(len(new_row)):
print(i)
if i < (len(new_row)-1):
f.write(new_row[i] "\n")
else:
f.write(new_row[i])
uj5u.com熱心網友回復:
因為index每次是 3 的倍數時都重置為 0,所以它永遠不會達到 9,并且if index % 3 == 0 and index != 9第 9 行的條件也將成立。洗掉index = 0應該可以解決問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/363817.html
上一篇:如何使用python函式從一個串列中生成一個以上的串列
下一篇:如何對這個公式求模?
