我一直在尝试读取计算机上的文件:
f = open("C:\\Users\\Yuzu\\Documents\\Python Data\file.txt", "w")
f.write("Hello")
f.close()
f = ("C:\\Users\\Yuzu\\Documents\\Python Data\file.txt", "rt")
print(f.read())
但是它说有一个属性错误并且还说元组不包含读取
答案 0 :(得分:0)
改变
f = ("C:\Users\Yuzu\Documents\Python Data\file.txt", "rt")
到
f = open("C:\Users\Yuzu\Documents\Python Data\file.txt", "rt")
答案 1 :(得分:0)
您忘记了 open
指令。应该是
f = open("C:\Users\Yuzu\Documents\Python Data\file.txt", "w")
f.write("Hello")
f.close()
f = open("C:\Users\Yuzu\Documents\Python Data\file.txt", "rt")
print(f.read())
否则,您只是将 f
声明为包含本地路径字符串和字符串 "rt"
的元组。
答案 2 :(得分:0)
通过添加 Open 函数更正您的代码
f = open("C:\Users\Yuzu\Documents\Python Data\file.txt", "rt")
答案 3 :(得分:0)
如果使用 close
,则不必使用 with open
。写入后文件自动关闭:
with open("C:\Users\Yuzu\Documents\Python Data\file.txt", "w") as file:
file.write("Hello")
答案 4 :(得分:0)
您在阅读时忘记了 open
。此外,您需要在所有地方使用另一个 \
转义 \
。
试试这个:
f = open("C:\\Users\\Yuzu\\Documents\\Python Data\\file.txt", "w")
f.write("Hello")
f.close()
f = open("C:\\Users\\Yuzu\\Documents\\Python Data\\file.txt", "rt")
print(f.read())
f.close()