如何遍历文件并按行创建新的字符串变量

时间:2016-11-03 18:00:22

标签: python file iteration

我通过文档阅读,但仍然无法弄清楚如何打开文件,读取每一行,将该行存储为新的字符串变量(暂时)。

我试过了:

file = file.open ("users.txt", r)

for user in users:
    user = users.readline ()
    ''' this is where I'd like to add something that creates user, user, until EOF '''
file.close ()

2 个答案:

答案 0 :(得分:0)

目前还不清楚你要做什么。

以下是Python习语中的概要(如果我理解的话):

您的代码 - 评论:

# file = file.open ("users.txt", r) NO! just use open' and don't use 'file' for a name

# for user in users:   What is 'users'?
    # user = users.readline () # if this is a file, just do 'for user in users: ...'
    ''' this is where I'd like to add something that creates user, user, until EOF '''
# file.close ()   # not necessary if you use `with`

修正:

with open("users.txt", r) as users:
   for user in users:
      # if each line of the file is a 'user' this gives you one user at a time

答案 1 :(得分:-2)

试试这个

var combinedList = list1.Concat(list2)     
                        .Concat(list3)
                        .Concat(list4)
                        .OrderByDescending(x => x.Fields["Press Release Date"] != null || x.Fields["Publish Date"] != null)
                        .ThenBy(x => x.Fields["Press Release Date"] != null ? x.Fields["Press Release Date"].ToString() : "")
                        .ThenBy(x => x.Fields["Publish Date"] != null ? x.Fields["Publish Date"].ToString() : "").ToList();

希望有所帮助。