Python3给文件追加换行时出现多余字符的问题排查与解决
问题排查与解决:文件追加换行时出现多余引号
问题原因
你误用了csv.writer的writerow()方法来追加换行,这是核心问题。csv.writer是专门生成CSV格式内容的工具,writerow()会把传入参数当作一行的字段列表处理。当你传入字符串'\n'时,Python会将字符串视为可迭代对象,把单个换行符当作独立字段,为符合CSV格式规范,这个特殊字段会被默认用双引号包裹,最终就出现了多余的引号。
输入文件内容
abc
错误代码示例
第一种写法:
with open(file_location, 'r') as file: data = file.read() if not data.endswith('\n'): with open(file_location, 'a') as newline_file: writer = csv.writer(newline_file) writer.writerow('\n')
第二种写法:
with open(local_file_location, 'r') as file: data = file.read() if not data.endswith('\n'): with open(local_file_location, 'a') as newline_file: writer = csv.writer(newline_file) writer.writerow("\n")
错误执行结果
abc" "
期望输出
abc
解决方法
不需要使用csv模块,直接用文件对象的write()方法追加换行符即可,代码修改如下:
with open(file_location, 'r') as file: data = file.read() if not data.endswith('\n'): with open(file_location, 'a') as newline_file: newline_file.write('\n')
或者简化为一次文件打开操作(用r+模式),减少IO开销:
with open(file_location, 'r+') as file: data = file.read() if not data.endswith('\n'): file.write('\n')
这两种写法都会直接在文件末尾追加纯换行符,不会引入多余引号,完全符合期望输出。
内容的提问来源于stack exchange,提问作者lostSoul
相关产品推荐
相关产品推荐

