首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用spyder编写和保存txt文件

使用spyder编写和保存txt文件
EN

Stack Overflow用户
提问于 2022-02-09 13:04:58
回答 1查看 466关注 0票数 0

我正在尝试从Python编写一个txt文件:

代码语言:javascript
复制
for i in range(len(X)):
    k+=1
    g.write('CoordinatesX='+str(i)+str(X[i])+'\n')
    g.write('D'+str(k)+'@Sketch'+str(sketch_number)+'=CoordinatesX'+str(k)+'\n')
    k+=1
    g.write('CoordinatesY='+str(i)+str(Y[i])+'\n')
    g.write('D'+str(k)+'@Sketch'+str(sketch_number)+'=CoordinatesY'+str(k)+'\n')
    k+=1
    g.write('CoordinatesZ='+str(i)+str(Z[i])+'\n')
    g.write('D'+str(k)+'@Sketch'+str(sketch_number)+'=CoordinatesZ'+str(k)+'\n')
        
g.close()

我没有发现错误,但是当我去查找下载的文件时,我找不到它,也没有写任何东西。有人知道我做错了什么吗?已经谢谢你了。干杯!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-09 13:06:58

在Python中,您可以这样open一个文件:

代码语言:javascript
复制
file = open('file.txt', 'r+')
file.read() # This will return the content
file.write("This file has just been overwritten")
file.close() # This will close the file

更好的做法是使用with/as语法:

代码语言:javascript
复制
with open('file.txt', 'r+') as file:
    file.read()
    file.write("This file has just been overwritten")
# The file is automatically closed (saved) after the with block has ended
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71050124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档