我想从目录中读取文件,并将每个文件的第一句写入新文件,直到100个字(或稍多于100个,因为我想写完成句子)写入新文件。关于读取文件总字数的疑问
我做以下列方式:
f = open(file1.txt, "w")
f.close()
for d_file in os.listdir(path):
d_file_path = os.path.join(path, d_file)
if os.path.isfile(d_file_path):
with open(d_file_path, "r") as f:
first = f.readline()
f1 = open ("file1.txt", "r")
textInput = f1.read()
f1.close()
l = len(textInput.split(' '))
print l
if l >= 0 and l <= 100:
f2 = open("file1.txt", "a")
f2.write(first)
print first
但是,我得到它打印语句输出错误,即使正确地写入新文件。
我的问题是: 为什么我会将“l
”的值为0两次? 此外,当我只需找到文件中的单词总数后,它已被写入:
>>>f = open(file1.txt, 'r')
>>> text = f.read()
>>> l = len(text.split(' '))
>>> print l
我得到:111
但是,该文件是:
An influential lawmaker from the governing Labor Party on Saturday backed Spanish requests to question former Chilean dictator Gen. Augusto Pinochet, in London for back surgery, on allegations of genocide and terrorism.
British police said Saturday they have arrested former Chilean dictator Gen. Augusto Pinochet on allegations of murdering Spanish citizens during his years in power.
Eight years after his turbulent regime ended, former Chilean strongman Gen. Augusto Pinochet is being called to account by Spanish authorities for the deaths, detention and torture of political opponents.
Former Chilean dictator Gen. Augusto Pinochet has been arrested by British police on a Spanish extradition warrant, despite protests from Chile that he is entitled to diplomatic immunity.
有没有114字?
有人可以回答我的问题吗?
编辑:
现在我做:l = len(textInput.strip().split())
,它给了我114个字作为计数,但打印语句仍然是相同的。现在的输出是这样的:
0
An influential lawmaker from the governing Labor Party on Saturday backed Spanish requests to question former Chilean dictator Gen. Augusto Pinochet, in London for back surgery, on allegations of genocide and terrorism.
0
British police said Saturday they have arrested former Chilean dictator Gen. Augusto Pinochet on allegations of murdering Spanish citizens during his years in power.
32
Eight years after his turbulent regime ended, former Chilean strongman Gen. Augusto Pinochet is being called to account by Spanish authorities for the deaths, detention and torture of political opponents.
56
Former Chilean dictator Gen. Augusto Pinochet has been arrested by British police on a Spanish extradition warrant, despite protests from Chile that he is entitled to diplomatic immunity.
86
President Fidel Castro said Sunday he disagreed with the arrest in London of former Chilean dictator Augusto Pinochet, calling it a case of international meddling.
114
114
114
114
114
这没有意义。如果你的file1.txt有你发布的内容,你的第一个打印语句应该打印114.为什么要打印0?并且在写完之后你还没有关闭文件。 – user3885927 2014-11-21 22:04:32
哦!对不起,我在问题中编辑了我的代码。看看有更好的理解。 file1.txt是在运行此循环之前创建的文件。 – 2014-11-21 22:08:52
哦!那是因为没有关闭文件。对于那个很抱歉。非常感谢! :D – 2014-11-21 22:17:07