python写入文件如何取消自动换行

后端开发   发布日期:2023年05月29日   浏览次数:50

python写入文件取消自动换行

问题描述

使用pycharm进行文件写入时,发现如果一行文字的长度过长,写入的过程则会自动换行,如何取消自动换行呢?

解决方法

将原来的

  1. f.write(line)

更改为

  1. f.write(line+'\n')

写入的文件默认在一行显示。每次完成写入后,自动换行到下一行,下次写入时便会在下一行写入。

python消除print的自动换行

对于python2.X,要消除print的自动换行,只需在print尾部加上一个逗号”,”,但是这一做法在python3.X就不适用了,这是为什么呢?

我们可以在交互式的环境下输入help(print),查询print的原理和使用方法。

Help on built-in function print in module builtins:

print(…)
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

  1. appledeMacBook-Pro-2:Desktop apple$ python3
  2. Python 3.5.0 (v3.5.0:374f501f4567, Sep 12 2015, 11:00:19)
  3. [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> help(print)
  6. Help on built-in function print in module builtins:
  7. print(...)
  8. print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  9. Prints the values to a stream, or to sys.stdout by default.
  10. Optional keyword arguments:
  11. file: a file-like object (stream); defaults to the current sys.stdout.
  12. sep: string inserted between values, default a space.
  13. end: string appended after the last value, default a newline.
  14. flush: whether to forcibly flush the stream.
  15. (END)

注意看这一句:

  1. print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

这一句说明在python3中print是一个函数,对于函数,其形参中有默认参数和关键参数。我们发现,在结尾处出现了end = ‘\n’,说明print是以\n结束的,end是默认参数。

只要我们在print中将默认参数的值改为空或者空格,就能实现不换行。

举个栗子:

  1. #!/usr/bin/python3
  2. # Filename: using_list.py
  3. # This is my shopping list
  4. shoplist = ['apple', 'mango', 'carrot', 'banana']
  5. print ('These items are:')
  6. for i in shoplist:
  7.     print (i,end=' ')
  8. # End

输出结果如下:

These items are:
apple mango carrot banana 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/qq_35090118/article/details/118461130

以上就是python写入文件如何取消自动换行的详细内容,更多关于python写入文件如何取消自动换行的资料请关注九品源码其它相关文章!