簡體   English   中英

想要在文件處理的下一行輸入數據。 我曾經嘗試使用 '\n' 但它不起作用

[英]Want to enter data in next line in file handling . I have used tried to use ‘\n’ but its not working

def addData(callno,bookname,author,year,qty):

  outfil=open('taxt.txt','a')
  outfil.write(str('\n'+callno).strip()+str(',').strip() + str(bookname).strip()+str(',').strip()+ str(author).strip()+str(',').strip()+ str(year).strip()+str(',').strip()+ str(qty).strip())


  outfil.close

strip() 方法去除所有空格,包括換行符。 您需要在添加\n字符之前調用 strip() ,而不是之后。

此外,您不需要對已經是字符串的東西調用 str() 和 strip()。

  outfil=open('taxt.txt','a')
  outfil.write('\n' + str(callno).strip() + ',' + str(bookname).strip() + ',' + str(author).strip() + ',' + str(year).strip() + ',' + str(qty).strip())
  outfil.close

順便說一句,您可以使用with運算符、str.join 和生成器表達式來簡化此操作。

with open("taxt.txt", "a") as outfile:
    outfile.write("\n" + ",".join(str(value).strip() for value in (callno, bookname, author, year, qty)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM