python寫(xiě)入文件如何取消自動(dòng)換行
python寫(xiě)入文件取消自動(dòng)換行
問(wèn)題描述
使用pycharm進(jìn)行文件寫(xiě)入時(shí),發(fā)現(xiàn)如果一行文字的長(zhǎng)度過(guò)長(zhǎng),寫(xiě)入的過(guò)程則會(huì)自動(dòng)換行,如何取消自動(dòng)換行呢?
解決方法
將原來(lái)的
f.write(line)
更改為
f.write(line+'\n')
寫(xiě)入的文件默認(rèn)在一行顯示。每次完成寫(xiě)入后,自動(dòng)換行到下一行,下次寫(xiě)入時(shí)便會(huì)在下一行寫(xiě)入。
python消除print的自動(dòng)換行
對(duì)于python2.X,要消除print的自動(dòng)換行,只需在print尾部加上一個(gè)逗號(hào)”,”,但是這一做法在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)
這一句說(shuō)明在python3中print是一個(gè)函數(shù),對(duì)于函數(shù),其形參中有默認(rèn)參數(shù)和關(guān)鍵參數(shù)。我們發(fā)現(xiàn),在結(jié)尾處出現(xiàn)了end = ‘\n’,說(shuō)明print是以\n結(jié)束的,end是默認(rèn)參數(shù)。
只要我們?cè)趐rint中將默認(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)簡(jiǎn)單驗(yàn)證碼的識(shí)別方法
這篇文章主要介紹了Python2.7+pytesser實(shí)現(xiàn)簡(jiǎn)單驗(yàn)證碼的識(shí)別方法,簡(jiǎn)單分析了pytesser的安裝及Python2.7環(huán)境下實(shí)現(xiàn)驗(yàn)證碼識(shí)別的相關(guān)操作技巧,需要的朋友可以參考下2017-12-12pytorch 數(shù)據(jù)加載性能對(duì)比分析
這篇文章主要介紹了pytorch 數(shù)據(jù)加載性能對(duì)比分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03對(duì)Python+opencv將圖片生成視頻的實(shí)例詳解
今天小編就為大家分享一篇對(duì)Python+opencv將圖片生成視頻的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01Python利用imshow制作自定義漸變填充柱狀圖(colorbar)
這篇文章主要介紹了Python利用imshow制作自定義漸變填充柱狀圖(colorbar),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12