[英]How to write bytes to a file?
我正在將一些 Python 2.7 代碼移植到 3.10,但我遇到了字節與字符串的問題。
我已將 .encode("utf-8") 添加到所有 .startswith 和 .endswith
我遇到的問題在最后,我得到了錯誤
...
destination.write("{}\n".format(delimiter.join(line_tokens)))
TypeError: sequence item 0: expected str instance, bytes found
如何糾正這個? 這是我的方法:
def fix_csv_file(csv_file_path, delimiter="\t"):
temp_file_path = "{}.temp".format(csv_file_path)
with open(csv_file_path, "rb") as source:
with open(temp_file_path, "wb") as destination:
for line in source:
# Remove carriage return and new line characters.
if line.endswith("\r\n".encode("utf-8")):
line = line[:-2]
elif line.endswith("\n".encode("utf-8")):
line = line[:-1]
# Clean up columns.
line_tokens = line.split(delimiter.encode("utf-8"))
for idx, token in enumerate(line_tokens):
token = token.strip()
if token == "(null)" or token == "\"(null)\"":
token = "\"\""
else:
if not token.startswith("\"".encode("utf-8")) and \
not token.endswith("\"".encode("utf-8")):
token = "\"{}\"".format(token)
line_tokens[idx] = token
destination.write("{}\n".format(delimiter.join(line_tokens)))
os.remove(csv_file_path)
os.rename(temp_file_path, csv_file_path)
這應該解決它。
def fix_csv_file(csv_file_path, delimiter="\t"):
temp_file_path = "{}.temp".format(csv_file_path)
with open(csv_file_path, "rt") as source:
with open(temp_file_path, "rt") as destination:
for line in source:
if line.endswith("\r\n"):
line = line[:-2]
elif line.endswith("\n"):
line = line[:-1]
line_tokens = line.split(delimeter)
for idx, token in enumerate(line_tokens):
token = token.strip()
if token == "(null)" or token == "\"(null)\"":
token = "\"\""
else:
if not token.startswith("\"") \
and not token.endswith("\""):
token = "\"{}\"".format(token)
line_tokens[idx] = token
destination.write("{}\n".format(delimiter.join(line_tokens)))
os.remove(csv_file_path)
os.rename(temp_file_path, csv_file_path)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.