这篇文章主要介绍了python写入文件如何取消自动换行问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
python写入文件取消自动换行
问题描述
使用pycharm进行文件写入时,发现如果一行文字的长度过长,写入的过程则会自动换行,如何取消自动换行呢?
解决方法
将原来的
f.write(line)更改为
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)
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是一个函数,对于函数,其形参中有默认参数和关键参数。我们发现,在结尾处出现了end = ‘\n’,说明print是以\n结束的,end是默认参数。
只要我们在print中将默认参数的值改为空或者空格,就能实现不换行。
举个栗子:
#!/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输出结果如下:
These items are:
apple mango carrot banana
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程学习网。
本文标题为:python写入文件如何取消自动换行
基础教程推荐
- Redis五种数据类型详解 2023-07-13
- centos7中redis安装 2023-09-12
- MySQL实现批量插入测试数据的方式总结 2023-08-12
- 还原Sql Server数据库BAK备份文件的3种方式以及常见错误总结 2023-07-29
- 关于对MongoDB索引的一些简单理解 2023-07-15
- SQL数据库十四种案例介绍 2023-08-12
- 在阿里云CentOS 6.8上安装Redis 2023-09-12
- Oracle 数据库启动过程的三阶段、停库四种模式详解 2023-07-23
- Redis中的BigKey问题排查与解决思路详解 2023-07-13
- mysql查询FIND_IN_SET REGEXP实践示例 2023-07-27
