Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent f.write to output the number of characters written?

Tags:

python-3.x

I use Python3 and write result into a file like this:

with open(output,'w') as f:
    f.write('Line count of the log files is: ' + str(line_count) + '. \n')

f.write() automatically returns # of characters written, is there a way to do not output it? I ask this because I do not want it output.

Thanks.

like image 585
Chenxi Zeng Avatar asked Dec 14 '16 18:12

Chenxi Zeng


People also ask

What does write () in Python return?

Description. Python file method write() writes a string str to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.

What is the difference between write and print in Python?

The "Write" statement will put "" around the data you are outputting and the "Print" statement will not. The "Print" statement will also output data to the screen as well as an open file, where the "Write" statement only outputs to an open file.

What is the mode string to use for opening files to write text?

You can do this with the write() method if you open the file with the "w" mode. As you can see, opening a file with the "w" mode and then writing to it replaces the existing content.

How do you write and print in Python?

The print() function takes the supplied string argument, appends a newline character to the end, and calls the stdout. write() method to write it to standard output. In the example above, we first print a line of text as we're accustomed to, which will be displayed in the console when we run the file.


1 Answers

This is not unique to file.write(). The interactive interpreter prints the result of any evaluated expression that does not result in None.

>>> for i in range(3):
...     i # expression evaluates to the value of i
...
0
1
2
>>> 

Two things to note. First, these won't be displayed when you are not using the interactive interpreter, so it's safe to ignore.

Second, you can make the display go away by assigning the result. That turns the expression into a statement.

>>> for i in range(3):
...     _ = i  # underscore is a nice meaningless variable name
...
>>>
like image 123
Steven Rumbalski Avatar answered Nov 23 '22 12:11

Steven Rumbalski