问题
I almost finished my project, but there is still one little problem. I want to write sensor values in a txt file with Python. All is working fine but one thing : in the txt file, there're blank lines between each value. It's really annoying because I can't put the values in a spreadsheet. It looks like That:
Sensor values:
2
4
6.32
1
etc....
When I want it that way :
Sensor values: 1 2 3 5 8 etc...
Here's the part of the code concerned :
def write_data():
global file_stream
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y %H_%M_%S")
file_stream = open("data " + dt_string+".txt", "w") # mode write ou append ?
write_lines()
def write_lines():
global after_id
data = arduinoData.read()
data2 = data.decode("utf-8")
file_stream.write(data2)
print(data2)
if data2 == "F":
print("Ca a marché")
stopacq()
return
after_id = root.after(10, write_lines)
Thanks
回答1:
Add the newline attribute
file_stream = open("data " + dt_string+".txt", "w", newline="")
回答2:
strip()
removes leading and trailing whitespace characters.
with open("directory/" + file, "r") as f:
for line in f:
cleanedLine = line.strip()
if cleanedLine: # is not empty
print(cleanedLine)
Use the following command to get the text file:
python file.py > file.txt
来源:https://stackoverflow.com/questions/60997312/blank-lines-in-txt-files-in-python