使用写入函数写入文件时出现断行 python
Line breakage when using write function to write to a file python
我使用写函数和 sys.stdout 在 python 脚本中打印到文件。问题是一行有很多字符,打印到文件时分成两行。我希望它打印在一行中。
前文-
“这是我要在文件中打印的文本,但由于长度问题,它最终写成了两行”
上面的文字是我需要的uotput,下面是我得到的输出
write(text) 或使用 sys.stdout 导致以下文本 -
输出行 1. "This is the text I want to print in the file, but it ends up writing "
输出行 2. "in two lines because of length"
我使用的代码如下,
out = subprocess.Popen(
['ls',path],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
for i in out.stdout:
if(re.search(r'(.*?)\.(out)',i)):
s = p+path+i+q+i
wp.write(s)
其中 p
、path
、i
、q
是连接并写入文件的不同字符串。抱歉此处显示的缩进错误!
write()
写入文件时不根据字符长度添加换行符。
根据您展示的内容以及我们在评论中的讨论,我可以自信地说 p
、path
、i
或 q
包含换行 ("\n"
) 字符。 (鉴于 path
与 ls
一起使用,我非常怀疑它在 path
中!)
在创建 s
后添加另一行代码,如下所示:
if "\n" in s:
print("Eureka! A new line exists!")
我使用写函数和 sys.stdout 在 python 脚本中打印到文件。问题是一行有很多字符,打印到文件时分成两行。我希望它打印在一行中。
前文- “这是我要在文件中打印的文本,但由于长度问题,它最终写成了两行” 上面的文字是我需要的uotput,下面是我得到的输出
write(text) 或使用 sys.stdout 导致以下文本 - 输出行 1. "This is the text I want to print in the file, but it ends up writing " 输出行 2. "in two lines because of length" 我使用的代码如下,
out = subprocess.Popen(
['ls',path],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
for i in out.stdout:
if(re.search(r'(.*?)\.(out)',i)):
s = p+path+i+q+i
wp.write(s)
其中 p
、path
、i
、q
是连接并写入文件的不同字符串。抱歉此处显示的缩进错误!
write()
写入文件时不根据字符长度添加换行符。
根据您展示的内容以及我们在评论中的讨论,我可以自信地说 p
、path
、i
或 q
包含换行 ("\n"
) 字符。 (鉴于 path
与 ls
一起使用,我非常怀疑它在 path
中!)
在创建 s
后添加另一行代码,如下所示:
if "\n" in s:
print("Eureka! A new line exists!")