如何从 python 结果创建“.scr”或“.txt”输出文件
Posted
技术标签:
【中文标题】如何从 python 结果创建“.scr”或“.txt”输出文件【英文标题】:how to create an ".scr" or ".txt" output file from python result 【发布时间】:2018-08-31 10:13:02 【问题描述】:首先,我必须告诉你,我是 python 的绝对菜鸟,并且 开始使用它希望能够创建小的可执行文件 基本工程任务。例如,下面的代码计算跟踪 铁路渐进曲线的坐标:
l=int(input('l='))
r=int(input('r='))
for x in range(0,l+1,2):
y=round(((x**3)/(6*l*r)),4)
for x in range(0,l+1,2):
grafic=print(x,",",round(((x**3)/(6*l*r)),4),sep='')
对于给定的变量值,输出:
l=42
r=195
0,0.0
2,0.0002
4,0.0013
6,0.0044
8,0.0104
10,0.0204
12,0.0352
14,0.0558
16,0.0834
18,0.1187
20,0.1628
22,0.2167
24,0.2813
26,0.3577
28,0.4467
30,0.5495
32,0.6668
34,0.7998
36,0.9495
38,1.1166
40,1.3024
42,1.5077
我正在尝试根据该结果创建一个“.scr”或“.txt”文件,它必须是:
pline
0,0.0
2,0.0002
4,0.0013
6,0.0044
8,0.0104
10,0.0204
12,0.0352
14,0.0558
16,0.0834
18,0.1187
20,0.1628
22,0.2167
24,0.2813
26,0.3577
28,0.4467
30,0.5495
32,0.6668
34,0.7998
36,0.9495
38,1.1166
40,1.3024
42,1.5077
我们的想法是创建一个可以在 ACAD 中导入的脚本文件,例如, 它跟踪二维折线的输出。 任何帮助将不胜感激!
【问题讨论】:
open
一个文件和write
到它。
与问题无关,但print
返回None
Create Text Document (Python)的可能重复
谢谢!我试过:f=open('trasare.txt','w') f.write(str(grafic)) f.close() 它创建一个只包含“None”的文件
How to redirect 'print' output to a file using python?的可能重复
【参考方案1】:
您可以使用 Python 的内置 open 函数创建文件:
with open('output.txt', 'w') as outfile:
outfile.write("pline\n")
l = int(input('l='))
r = int(input('r='))
for x in range(0, l + 1, 2):
y = round(((x ** 3) / (6 * l * r)), 4)
for x in range(0, l + 1, 2):
outfile.write(",\n".format(x, round(((x ** 3) / (6 * l * r)), 4)))
输出
pline
0,0.0
2,0.0002
4,0.0013
6,0.0044
8,0.0104
10,0.0204
12,0.0352
14,0.0558
16,0.0834
18,0.1187
20,0.1628
22,0.2167
24,0.2813
26,0.3577
28,0.4467
30,0.5495
32,0.6668
34,0.7998
36,0.9495
38,1.1166
40,1.3024
42,1.5077
函数outfile.write
将文本写入文件,在上面的示例中为outfile
。要写一行,你必须在你写的每个字符串的末尾附加换行符\n
。
【讨论】:
太棒了!很高兴我能帮忙【参考方案2】:你可以使用write
以文本文件的形式打开您的文本文件
使用 \n 换行
使用textfile.write
【讨论】:
以上是关于如何从 python 结果创建“.scr”或“.txt”输出文件的主要内容,如果未能解决你的问题,请参考以下文章
Felix/OSGi:如何使用不是 OSGi 服务的 SCR 组件?