Python Forum
Writing string to file results in one character per line
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writing string to file results in one character per line
#5
Your original code:

def write_to_log(s):
	# open the file in append mode
	with open('/home/bs/NAS_2/projects/Raspberry_pi/Temperature/log.txt', 'a') as f:
		# write the line to the text file
		f.write('\n'.join(line));
Note that your function expects parameter s, but it is never used. You actually use line and your code sort of works, only because there is line variable in global scope.
As to the problem you face - when you use '\n'.join(some_string) new-line is inserted between each char of the string
>>> foo = 'spam'
>>> eggs = '\n'.join(foo)
>>> eggs
's\np\na\nm'
>>> print(eggs) # same would be if you write to file
s
p
a
m
>>>
def write_to_log(log_msg):
	# open the file in append mode
	with open('/home/bs/NAS_2/projects/Raspberry_pi/Temperature/log.txt', 'a') as f:
		# write the line to the text file
		f.write(f'{log_msg}\n')
Right now the log file is hardcoded in the function, but you can pass it as argument.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Writing string to file results in one character per line - by buran - Sep-27-2022, 01:38 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Writing a Linear Search algorithm - malformed string representation Drone4four 10 1,191 Jan-10-2024, 08:39 AM
Last Post: gulshan212
  Updating sharepoint excel file odd results cubangt 1 976 Nov-03-2023, 05:13 PM
Last Post: noisefloor
  Need to replace a string with a file (HTML file) tester_V 1 854 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,858 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  Getting last line of each line occurrence in a file tester_V 1 949 Jan-31-2023, 09:29 PM
Last Post: deanhystad
  Trying to send file to printer with no results. chob_thomas 2 3,555 Dec-21-2022, 07:12 AM
Last Post: Pedroski55
  Inserting line feeds and comments into a beautifulsoup string arbiel 1 1,257 Jul-20-2022, 09:05 AM
Last Post: arbiel
  Writing to json file ebolisa 1 1,083 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Writing to External File DaveG 9 2,665 Mar-30-2022, 06:25 AM
Last Post: bowlofred
  Print to a New Line when Appending File DaveG 0 1,276 Mar-30-2022, 04:14 AM
Last Post: DaveG

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020