在内置的蟒蛇开放的功能,是个什么模式之间准确的区别w,a,w+,a+,和r+?
特别是,文档暗示所有这些都允许写入文件,并说它打开文件"具体"附加",写入"和"更新",但没有定义这些术语的含义.
我做了一个简单的程序,但是当我运行它时会显示以下错误:
line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")
file = open("File.txt","w")
for i in range(3):
file.write(line1[i])
file.write("\n")
for line in file:
print(line)
file.close()
Run Code Online (Sandbox Code Playgroud)
它显示以下错误消息:
文件"C:/ Users/Sachin Patil/fourth,py.py",第18
行,输入文件中的行:UnsupportedOperation:不可读
我想以覆盖模式将 pandas 数据帧保存到 csv。我希望每当程序再次运行并进行任何更改时,它都应该将数据帧保存到 csv 并覆盖该位置已保存的 csv 文件。
我在做一些文件IO时偶然发现了这个stackoverflow问题:被python文件模式“ w +”弄糊涂了
r阅读w用于写作r+打开以进行读写(无法截断文件)w+用于读写(可以截断文件)rb+读取或写入二进制文件wb+编写二进制文件a+打开进行追加
请注意,r+不能截断文件。因此,我一直在寻找可以在读取文件后截断文件的东西,这导致我转到了另一个SO链接:Python在读取行时截断了行
我看到他们使用了另一种模式rw+,该模式没有记录。从答案中使用它的方式来看,我猜想它的意思是“开放供阅读,书写和截断,但不截断开放”。
后来我测试了这种模式,似乎它已在Python 3中删除,因此ValueError在使用时抛出了一个:
Python 2:
f = open("myfile.txt", "rw+")
text = f.read()
f.truncate(0)
f.close()
Run Code Online (Sandbox Code Playgroud)
Python 3:
f = open("myfile.txt", "rw+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: must have exactly one of create/read/write/append mode
Run Code Online (Sandbox Code Playgroud)
但是,我需要Python 3中的文件模式,该文件模式可以截断和读取,但不能在打开时截断。因此,经过更多测试,我发现它r+实际上可以在Python 2和3中截断。
Python 2:
f = open("myfile.txt", "r+")
text = f.read()
f.truncate(0) …Run Code Online (Sandbox Code Playgroud) 我在 Windows 上,我的目录中不存在任何文件。
我很难弄清楚原因:
fid = open('L01A.txt', 'x')
fid.write('A')
fid.close()
fid = open('L01a.txt', 'x')
fid.write('a')
fid.close()
Run Code Online (Sandbox Code Playgroud)
给我:
[错误 17] 文件存在:'L01a.txt'。
所以我试图创建一个文件并从中读取,即使它是空的。因此,下次运行该程序时,该文件将已经存在并且其中会有数据。
#this should create the file
filename = open("roombooking.bin","wb")
#this should load the data into a list but since its first created it should be an empty list
monday=pickle.load(open("roombooking.bin","rb"))
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误
Traceback (most recent call last):
monday=pickle.load(open("roombooking.bin","rb"))
File "C:\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Python27\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python27\lib\pickle.py", line 880, in load_eof
raise EOFError
EOFError
Run Code Online (Sandbox Code Playgroud) 我从命令readline()得到了什么.我是python的新手,现在完全糊涂了.
my_file = open("test.txt", "w+")
my_file.write("This is a test")
print my_file.readline()
Run Code Online (Sandbox Code Playgroud) python ×7
file-io ×2
python-3.x ×2
file ×1
naming ×1
pandas ×1
pickle ×1
python-2.7 ×1
python-2.x ×1