Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python f、 读空了_Python_String_File - Fatal编程技术网

Python f、 读空了

Python f、 读空了,python,string,file,Python,String,File,这一切都是我在翻译室里做的 loc1 = '/council/council1' file1 = open(loc1, 'r') 此时,我可以执行file1.read(),它将文件内容作为字符串打印到标准输出 但是如果我加上这个 string1 = file1.read() 字符串1返回为空。。我不知道我会做错什么。这似乎是最基本的事情 如果继续键入file1.read(),则标准输出的输出只是一个空字符串。因此,当我尝试使用file1.read()创建字符串时,不知何故我丢失了文件。请确保

这一切都是我在翻译室里做的

loc1 = '/council/council1'
file1 = open(loc1, 'r')
此时,我可以执行file1.read(),它将文件内容作为字符串打印到标准输出

但是如果我加上这个

string1 = file1.read()
字符串1返回为空。。我不知道我会做错什么。这似乎是最基本的事情


如果继续键入file1.read(),则标准输出的输出只是一个空字符串。因此,当我尝试使用file1.read()创建字符串时,不知何故我丢失了文件。请确保您的位置正确。您的根目录(
/
)下是否有一个名为
/council
的目录?。还可以使用,
os.path.join()
创建路径

loc1 = os.path.join("/path","dir1","dir2")

一个文件只能读取一次。之后,当前读取位置位于文件末尾

如果在重新阅读前添加
file1.seek(0)
,则应该能够再次阅读内容。但是,更好的方法是第一次读入字符串,然后将其保存在内存中:

loc1 = '/council/council1'
file1 = open(loc1, 'r')
string1 = file1.read()
print string1

您不会丢失它,只需将偏移量指针移动到文件的末尾,并尝试读取更多数据。因为它是文件的结尾,所以没有更多的数据可用,您将得到空字符串。尝试重新打开文件或寻求零位置:

f.read()
f.seek(0)
f.read()

一起使用是最好的语法,因为它会在使用文件后关闭与该文件的连接(从python 2.5开始):


这并不能回答问题。
with open('/council/council1', 'r') as input_file:
   text = input_file.read()
print(text)