gpt4 book ai didi

python - MacOS 上的 PyCharm 无法处理文件

转载 作者:行者123 更新时间:2023-12-01 01:44:22 25 4
gpt4 key购买 nike

我现在正在学习 Python,并尝试在 MacOS 上使用 PyCharm CE 学习文件处理。在尝试打开或创建新文件时,我收到类似以下内容的错误 -

io.UnsupportedOperation: not readable

我的代码看起来像这样:

import os             
print (os.path.abspath(os.curdir))

fhand = open("file1.rtf", "w")

for line in fhand:
if line.startswith("from :") :
line = line.strip()
print(line)

如何打开文件并在其中写入内容?这段代码有什么问题?

最佳答案

您以错误的模式打开了文件。这与 PyCharm 无关,但与您的代码有关:)

如果您用 python(或大多数其他编程语言)打开文件,则必须指定是要读取它还是写入它。您有更多的选择,但让我们保持简单。

为此,您可以使用 open() 函数的第二个参数,在您的例子中为 "w",它代表 write.

如果您想阅读,请将其更改为“r”:

fhand = open("file1.rtf", "r")

如果您想读取写入,您可以使用诸如w+之类的东西。要获得概述,您可以找到 this diagram有用。

来自docs :

open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

f = open('workfile', 'w')

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

关于python - MacOS 上的 PyCharm 无法处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51555834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com