简体   繁体   English

如何在 Spyder 中读取/写入文件

[英]How do I read/write to files in Spyder

1.I am new to coding and I store all my python code in: 1.我是编码新手,我将所有 python 代码存储在:

C:\Users\(MyName)\Documents\Python Scripts

2.I made a txt file in notepad (list.txt) and stored it in the same location 2.我在记事本(list.txt)中制作了一个txt文件并存储在同一个位置

3.I want to read the file so in Spyder: 3.我想在 Spyder 中读取文件:

file = open('list.txt', 'r')
print(file.read())
file.close()

4.I get an error 4.我收到一个错误

FileNotFoundError: [Errno 2] No such file or directory: 'list.txt'

5.Where am I supposed to store my txt file? 5.我应该在哪里存储我的txt文件? And how do I read it?我如何阅读它?

Make sure you have the script in the same directory as the file, or change the path to the correct directory path.确保脚本与文件位于同一目录中,或将路径更改为正确的目录路径。

A possible solution is using numpy.loadtxt and numpy.savext .一种可能的解决方案是使用numpy.loadtxtnumpy.savext Eg:例如:

import numpy as np

example_list = [1,2,3,4]
np.savetxt('example_file.txt',example_list)
data = np.loadtxt ('example_file.txt')
print(data)

>>> [1. 2. 3. 4.]

It should work on the same directory your console or py file are located它应该在您的控制台或 py 文件所在的同一目录上工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Python 读写 CSV 文件? - How do I read and write CSV files with Python? 如何在Python中读/写xlsx和xls文件? - How do I read/write both xlsx and xls files in Python? 如何使用 Spyder 启动所有 .py 文件? - How do I make all .py files launch with Spyder? 如何读写二进制文件? - How can I read and write binary files? 如何读取多个文本文件并一一处理并将其写入Excel文件 - How do I read multiple text files and process it one by one and write rows into a excel file 如何读取两个 CSV 文件,然后合并它们的数据,并在 Python 中写入一个 CSV 文件? - How do i read two CSV files, then merge their data, and write to one CSV file in Python? 如何编写代码以使用 tifffile 库读取 TIFF 文件并将它们转换为 JPEG? - How do I write code to use the tifffile library to read TIFF files and convert them to JPEGs? 如何编写可读取doc / docx文件并将其转换为txt的python脚本? - How do I write a python script that can read doc/docx files and convert them to txt? 如何在一行中将输入写入文件并将多个输入存储到文件中并能够读取它们? - How do I write input to files in one line and store multiple inputs to the file and be able to read them? 如何使用 msgpack 进行读写? - How do I read and write with msgpack?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM