python寫入文件如何取消自動換行
python寫入文件取消自動換行
問題描述
使用pycharm進(jìn)行文件寫入時(shí),發(fā)現(xiàn)如果一行文字的長度過長,寫入的過程則會自動換行,如何取消自動換行呢?
解決方法
將原來的
f.write(line)
更改為
f.write(line+'\n')
寫入的文件默認(rèn)在一行顯示。每次完成寫入后,自動換行到下一行,下次寫入時(shí)便會在下一行寫入。
python消除print的自動換行
對于python2.X,要消除print的自動換行,只需在print尾部加上一個(gè)逗號”,”,但是這一做法在python3.X就不適用了,這是為什么呢?
我們可以在交互式的環(huán)境下輸入help(print),查詢print的原理和使用方法。
Help on built-in function print in module builtins:
print(…)
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
appledeMacBook-Pro-2:Desktop apple$ python3 Python 3.5.0 (v3.5.0:374f501f4567, Sep 12 2015, 11:00:19) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. (END)
注意看這一句:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
這一句說明在python3中print是一個(gè)函數(shù),對于函數(shù),其形參中有默認(rèn)參數(shù)和關(guān)鍵參數(shù)。我們發(fā)現(xiàn),在結(jié)尾處出現(xiàn)了end = ‘\n’,說明print是以\n結(jié)束的,end是默認(rèn)參數(shù)。
只要我們在print中將默認(rèn)參數(shù)的值改為空或者空格,就能實(shí)現(xiàn)不換行。
舉個(gè)栗子:
#!/usr/bin/python3 # Filename: using_list.py # This is my shopping list shoplist = ['apple', 'mango', 'carrot', 'banana'] print ('These items are:') for i in shoplist: ? ? print (i,end=' ') # End
輸出結(jié)果如下:
These items are:
apple mango carrot banana
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python2.7+pytesser實(shí)現(xiàn)簡單驗(yàn)證碼的識別方法
這篇文章主要介紹了Python2.7+pytesser實(shí)現(xiàn)簡單驗(yàn)證碼的識別方法,簡單分析了pytesser的安裝及Python2.7環(huán)境下實(shí)現(xiàn)驗(yàn)證碼識別的相關(guān)操作技巧,需要的朋友可以參考下2017-12-12對Python+opencv將圖片生成視頻的實(shí)例詳解
今天小編就為大家分享一篇對Python+opencv將圖片生成視頻的實(shí)例詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01Python利用imshow制作自定義漸變填充柱狀圖(colorbar)
這篇文章主要介紹了Python利用imshow制作自定義漸變填充柱狀圖(colorbar),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12