您的位置:首頁技術文章
文章詳情頁

python - 為什么寫了換行語句,結果還是沒有換行?

瀏覽:85日期:2022-06-27 10:52:29

問題描述

想把文件冒號后面的數字,按照每行寫入另一個文件,在每行末尾換行,用以下代碼,有換行語句,結果還是沒換行,怎么辦?python - 為什么寫了換行語句,結果還是沒有換行?

#!/usr/bin/python#coding:utf-8import pickleimport retfidf_dict={}tfidf_all=[]with open(’/home/user1/zhouchun/lda/KNN/single_tfidf.txt’,’a’) as file:with open(’/home/user1/zhouchun/lda/KNN/train_tfidf.txt’, ’r’) as fw:# content = fw.readlines()for line in fw: index_tfidf=line.split() # print index_tfidf for j in index_tfidf:m=re.compile(r’^(d+):(d+)$’)try: word_index=m.match(j).group(1) tfidf=m.match(j).group(2) file.write(str(tfidf) + ’ ’)except: word_index=None tfidf=Nonefile.write(’n’)

python - 為什么寫了換行語句,結果還是沒有換行?

問題解答

回答1:

windows上換行應該為rn. 所以file.write(’rn’).

回答2:

縮進不對。

python - 為什么寫了換行語句,結果還是沒有換行?

回答3:

with open(’a.txt’, ’r’) as f1, open(’b.txt’, ’a’) as f2: for line in f1:new_line = [_.split(’:’)[1] for _ in line.split()]f2.write(’ ’.join(new_line))f2.write(’n’)

標簽: Python 編程
国产综合久久一区二区三区