【发布时间】:2012-08-04 15:11:20
【问题描述】:
我正在尝试从每个文件中获取信息并使用它来创建一个新文件。每个文件都有一行,由一系列数字组成。我希望一个文件的每一行与另一个文件的每一行对齐,然后将一个文件的一行中的每个数字与另一个文件中另一行的同一位置的另一个数字相遇。文件“Volume.txt”的每一行都移动了一个点(因此代码 k = j+1)。
*操作完成后,我不断得到一个汉字重复很多次。那么我哪里做错了?非常感谢!*
代码如下:
e = open('C:/Users/MC/Desktop/EODP.txt', 'r')
v = open('C:/Users/MC/Desktop/Z/Volume.txt', 'r')
n = open('C:/Users/MC/Desktop/vovere.txt', 'w')
m = 0 #Used later for letting me know that the first line in the new file completed
for i in range(0, 3256): # there are 3257 lines per the two files EOPD and Volume
l = [] # create a list to put data in during operation
er = e.readline() #
es = er.split(', ') # create a list the data from that line of file
vr = v.readline() #
vs = vr.split(', ') # same
for j in range(len(es)):
k = j + 1 # file Volume is shifted one point ahead
try:
if float(vs[k]) == 0.0:
vovere = 0.0 # vovere is the name of the output for each point
elif vs[k] == '' or vs[k] == ' ':
vovere = 0.0
else:
vovere = float(es[j])/float(vs[k])
except ValueError: #kept getting this error: some points weren't numbers
vovere = 0.0
except IndexError: # Each file didn't always exactly equal in line length
vovere = 0.0
la = l.append(float(vovere)) #Creates the list for each new line in new file
ls = str(la)
l1 = ls.replace('[', '') # Taking away extra notations so the new file is a little
l2 = l1.replace(']', '') # more clean and can be put into other programs
n.write(l2)
if m == 0: # From here on out is just for me, not necessary**
print("The first line is done!")
m += 1
else:
pass
e.close() #** Except these of course
print(e.closed)
print("Yes, EOPD.txt is closed")
v.close()
print(v.closed)
print("Yes, Volume.txt is closed")
n.close()
print(n.closed)
print("Yes, vovere.txt is now ready for further manipulation!!")
【问题讨论】:
-
问题不清楚,是每个文件只有一行还是每个文件有多行?如果每个文件中有不止一行,那么每一行是否有多个数字?如果一行有多个数字,分隔符是什么?我几乎跳过了阅读您的代码,因为编写更短的内容似乎更容易完成问题文本部分中描述的工作。
-
很抱歉给您带来了困惑。我从中提取的两个文件各有多行。每行有多个数据点,每个数据点用逗号隔开,然后用空格隔开。我正在尝试将一个文件的第一行与另一个文件的第一行进行匹配,然后将 EODP.txt 中的数据点 1 和 Volume.txt 中的数据点 2 匹配,以及两行中指向的所有其他数据,令人震惊相对位置。我希望为后续的每一行重复此操作。每个文件的行数相同,但每行使用的数据点数不一定相同。希望对您有所帮助,谢谢!
-
交错点含义:文件卷,第 1 行,第 2 点与文件 EODP,第 1 行,第 1 点。然后是文件卷,第 1 行,第 3 点与文件 EODP,第 1 行,第 2 点。重复对于文件 EODP 第 1 行的整个长度,应该有 lenth len(volume line 1)-1。
-
这个问题有很多重复的地方。只需搜索“python 合并文件”。
标签: python exception-handling python-3.x file-handling