Issue: Csv.writer (). Writerow () saved CSV file, open with more lines after each line
Workaround: Add a parameter to the open () newline= "
problem Phenomenon:1. Code
with open ("C:\\users\\xxx\\desktop\\redis_ Log2.csv "," W ") as Datacsv:
Csvwriter = Csv.writer (datacsv,dialect= ("Excel"))
for info in parsecsv:
Csvwriter.writerow ([info["Time"],info ["Us"],info["sy"],info["CL"],info["BCL"],info["mem"],info["RSS"],info["Keys"],info["cmd/s"],\
info["exp/s"],info["evt/s"],info["hit%/s"],info["hit/s"],info["mis/s"],info["Aofcs"]])
2. The exported CSV opens in Excel:
After the change.
1. Code
With open ("C:\\users\\xxx\\desktop\\redis_log2.csv", "W", newline=") as Datacsv:
Csvwriter = Csv.writer (datacsv,dialect= ("Excel"))
Csvwriter.writerow (["Time", "Us", "sy", "CL", "BCL", "Mem", "RSS", "Keys", "cmd/s", "exp/s", "evt/s", "hit%/s", "hit/s", " MIS/S "," Aofcs "])
For info in Parsecsv:
Csvwriter.writerow ([info["Time"],info["Us"],info["sy"],info["CL"],info["BCL"],info["mem"],info["RSS"],info[" Keys "],info[" cmd/s "],\
info["exp/s"],info["evt/s"],info["hit%/s"],info["hit/s"],info["mis/s"],info["Aofcs"])
2. The exported CSV opens in Excel:
explanation of the newline parameter:
The parameter newline is used to control the end character of a line below the text pattern. Can be none, ' ', \n,\r,\r\n and so on.
When in read mode, if the new line character is none, then it works as a generic line break pattern, meaning that when encountering \n,\r or \ r \ n, it can be used as a newline identifier and uniformly converted to \ n as the text input line break. When set to null ', it is also common line break mode work, but do not convert to \ n, enter what kind of, will remain the full input. When set to a different character, the corresponding character is judged to be the line break and is entered as-is into the text.
When in output mode, if the new line character is none, all output text takes \ n as the newline character. If set to ' or \ n ', no substitution action is made. If it is another character, it is added after the character \ n as the line break.
Python3 using the CSV Module Csv.writer (). Writerow () Save the CSV file, resulting in a blank line problem