我发现最后的文件是空的,python
如果需要你的帮助,我想把一个文件中的一些特定行复制到另外两行。 变量n和p是全局变量。 这是我的密码:我发现最后的文件是空的,python,python,Python,如果需要你的帮助,我想把一个文件中的一些特定行复制到另外两行。 变量n和p是全局变量。 这是我的密码: def files(): i = 1 X = 1 f90 = open('C:\Users\Homura\Desktop\python\data90.txt' , 'w') f10 = open('C:\Users\Homura\Desktop\python\data10.txt' , 'w') f = open('C:\Users\Homura\Des
def files():
i = 1
X = 1
f90 = open('C:\Users\Homura\Desktop\python\data90.txt' , 'w')
f10 = open('C:\Users\Homura\Desktop\python\data10.txt' , 'w')
f = open('C:\Users\Homura\Desktop\python\TData.txt' , 'r')
while True:
line = f.readline()
if line.startswith('0'):
while i <= n: # taking 90% of negative tweets and writing them in f90
f90.write(line)
i += 1
while i != n: #putting the rest of the negative tweets ( 10%) in the f10 file
f10.write(line)
i += 1
elif line.startswith('1'):
while ( x <= p): # taking 90% of positive tweets and writing them in f90
f90.write(line)
x += 1
while (x != p): #putting the rest of the positive tweets ( 10%) in the f10 file
f10.write(line)
x += 1
f.close()
f10.close()
f90.close()
return f10 , f90
def文件():
i=1
X=1
f90=打开('C:\Users\Homura\Desktop\python\data90.txt','w')
f10=open('C:\Users\Homura\Desktop\python\data10.txt','w')
f=open('C:\Users\Homura\Desktop\python\TData.txt','r')
尽管如此:
line=f.readline()
如果行.startswith('0'):
首先是一个小观察,你有一个大写的X
和一个小写的X
——它们应该是一样的吗
X = 1
#...
x += 1
下一步,很有可能台词不是以你认为的字符开头。
考虑添加另一个来捕获< <代码> 0 < /代码>或<代码> 1 <代码>开始。
最后,由于您说while True
不清楚while循环将如何终止,因此可能不会终止,并且文件永远不会关闭。尝试只为文件中的行执行。。。(参见示例)
试试这个:
for line in f:
if line.startswith('0'):
while i <= n: # taking 90% of negative tweets and writing them in f90
f90.write(line)
i += 1
while i != n: #putting the rest of the negative tweets ( 10%) in the f10 file
f10.write(line)
i += 1
elif line.startswith('1'):
while ( x <= p): # taking 90% of positive tweets and writing them in f90
f90.write(line)
x += 1
while (x != p): #putting the rest of the positive tweets ( 10%) in the f10 file
f10.write(line)
x += 1
else:
print "Unmatched line ", line
尝试将其更改为原始字符串
f = open(r'C:\Users\Homura\Desktop\python\TData.txt' , 'r')
请解释你的问题,你尝试了什么,你想让程序做什么,你说的“compy”是什么意思?s/wanrt/want s/compy/copy?也许如果你能从你的文件中提供一个示例行,我们可以帮你更多。对于录制错误,我很抱歉,我想复制90%的推文(以0或1开头的行)两个文件f90和一个名为f10的文件中的其他tweet。非常感谢您的帮助,但它不是工作文件“\first.py”,第64行如果line.startswith('0'):^IndentationError:预期缩进块缩进错误通常意味着您有一堆制表符和空格。我复制了您给我的内容,我遇到了这个问题,我不认为我们需要缩进,但是python更清楚:Dplease,你这是什么意思,我使用记事本+++i使用制表符缩进i使用空格缩进-你需要保持一致。
f = open(r'C:\Users\Homura\Desktop\python\TData.txt' , 'r')