SoFunction
Updated on 2024-11-12

How to cancel automatic line feeds when writing to a file in python

python writes to a file to cancel automatic line feeds

Description of the problem

When using pycharm to write a file, I found that if the length of a line of text is too long, the writing process will automatically line feed, how to cancel the automatic line feed?

cure

replacing the original

(line)

change to

(line+'\n')

The written file is displayed on one line by default. Each time you finish writing, you will automatically newline to the next line, and the next time you write, you will write on the next line.

python eliminates automatic line breaks in print

To eliminate automatic line breaks in print, simply add a comma "," to the end of print, but this does not work anymore.

We can type help(print) in an interactive environment to query how print works and how to use it.

Help on built-in function print in module builtins:

print(…)
print(value, …, sep=’ ‘, end=’\n’, file=, 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=, flush=False)
    Prints the values to a stream, or to  by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current .
    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) 

Look at this sentence.

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

This sentence indicates that print is a function in python3, and for functions, there are default and key parameters in their formal parameters. We notice that end = '\n' appears at the end, indicating that print ends with \n and end is the default argument.

As long as we change the value of the default parameter in print to null or space, we can achieve no line breaks.

Take a chestnut:

#!/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

The output is as follows:

These items are:
apple mango carrot banana 

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.